Start learning free

LESSON 256 OF 287 · NESTED LOOPS OVER GRIDS

Count in a Grid in Python: Counting Matching Cells

Practice Read the full explanation

Given a grid of integers grid and an integer target, return how many cells of the grid are equal to target.

A grid is a list of rows, and each row is a list of integers.

 

Example 1:

Input: grid = [
  [1, 2, 3],
  [4, 2, 6],
  [2, 8, 2]
], target = 2
Output: 4
Explanation: 2 appears once in the first row, once in the second row and twice in the third row: 1 + 1 + 2 = 4.

Example 2:

Input: grid = [
  [-1, 5],
  [5, -1]
], target = -1
Output: 2
Explanation: The two cells with -1 are in different rows, and each one counts.

Example 3:

Input: grid = [
  [7, 8, 9]
], target = 4
Output: 0
Explanation: No cell is equal to 4.

 

Constraints:

  • grid has at least 1 row and 1 column, and every row has the same number of values.
  • Every value and target is an integer between -1000 and 1000; they can be negative.
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · NESTED LOOPS OVER GRIDS

    Count In Grid in Python, explained

    Problem overview

    The method countInGrid receives grid, a list of rows where each row is a list of integers, and an integer target. It returns how many cells of the grid equal target.

    For a grid with rows [1, 2, 3], [4, 2, 6] and [2, 8, 2] and target = 2, the value 2 appears once in the first row, once in the second and twice in the third: the answer is 4. For [[-1, 5], [5, -1]] with target = -1 the answer is 2, because the two matches are in different rows and each counts. For [[7, 8, 9]] with target = 4 nothing matches, so the answer is 0.

    Approach

    Counting matches is the counter pattern you know from flat lists, applied at two levels. Start a counter at 0, visit every cell, and add 1 whenever the cell equals the target. Visiting every cell of a grid takes a loop over the rows with a loop over each row's values inside it.

    Unlike a search, this problem never stops early: a match does not end the work, because later cells may match too. The function has to look at every cell before it answers.

    Step by step

    1. Create count = 0. No cell has been checked, so no match is found yet.
    2. Loop row over grid. Each row is a list of integers.
    3. Loop value over row. The inner loop covers a whole row before the outer loop moves down, so every cell is visited exactly once.
    4. If value == target, add 1 to count. Any other value is skipped.
    5. Return count after both loops, once every cell has been checked.

    The solution in Python

    class Solution:
        def countInGrid(self, grid: List[List[int]], target: int) -> int:
            count = 0
            for row in grid:
                for value in row:
                    if value == target:
                        count += 1
            return count
    

    Python details:

    • == compares, = assigns. Writing if value = target: is a syntax error in Python.
    • The if sits inside the inner loop. Its indentation decides that it runs once per cell. Placed at the outer loop's level, it would test only the last value of each row.
    • Negative targets work like any other integer: -1 == -1 is true.

    Python's lists have a count method, so each row's matches are row.count(target). Adding those up, sum(r.count(target) for r in grid), gives the same result as the nested loops. The loops show the work that count does inside.

    Edge cases and common mistakes

    • Stopping at the first match. A return inside the if would answer 1 for the first example instead of 4. Count, then return after the loops.
    • Counting rows instead of cells. A row with the target twice, like the last row of the first example, adds 2, not 1.
    • Returning inside a loop. The function would stop after the first row or the first cell.
    • No match. The counter is never incremented and the function returns 0, with no special case.
    • Zero as a target. It is an ordinary value; nothing treats it as "empty".

    Testing

    • [[1, 2, 3], [4, 2, 6], [2, 8, 2]] with target 2 gives 4.
    • [[-1, 5], [5, -1]] with target -1 gives 2.
    • [[7, 8, 9]] with target 4 gives 0.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free