Start learning free

LESSON 260 OF 285 · NESTED LOOPS OVER GRIDS

Count in Grid in Go: 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 an array of rows, and each row is an array 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

    GO · NESTED LOOPS OVER GRIDS

    Count In Grid in Go, explained

    Problem overview

    The function countInGrid receives a grid, grid of type [][]int, and an integer target. It returns how many cells of the grid are equal to target.

    For the grid [[1, 2, 3], [4, 2, 6], [2, 8, 2]] and target = 2 the answer is 4: one 2 in the first row, one in the second and two in the third. For [[-1, 5], [5, -1]] and target = -1 the answer is 2, because the two cells are in different rows and each one counts. For [[7, 8, 9]] and target = 4 the answer is 0.

    Approach: visit every cell and count the matches

    This is the counting pattern applied to two dimensions. Keep a counter that starts at 0. Visit every cell with two nested loops, the outer one over rows and the inner one over the values in the current row. Whenever a value equals target, add 1. After the loops, the counter holds the number of matches.

    No cell needs to be remembered or skipped, and the position of a match does not matter, only that it exists. That is why range with the index dropped is enough.

    Step by step

    1. Create count with :=, starting at 0.
    2. Loop over the rows: for _, row := range grid. A [][]int is a slice of rows, so each row is a []int.
    3. Loop over the row's values: for _, value := range row. The inner loop finishes a whole row before the outer loop moves on, so every cell is visited exactly once.
    4. Compare and count: if value == target, run count++. Other values are skipped.
    5. Return count after both loops, so every cell has been checked first.

    The solution in Go

    func countInGrid(grid [][]int, target int) int {
        count := 0
        for _, row := range grid {
            for _, value := range row {
                if value == target {
                    count++
                }
            }
        }
        return count
    }
    

    Go details:

    • == compares values. For two int values, value == target is true when they are the same number. A single = is assignment, and using it in an if does not compile.
    • count++ is a statement. It adds 1 to count. Go has no ++count and doesn't let count++ be used inside a larger expression.
    • Parameter types. The signature grid [][]int, target int reads as "a slice of slices of int, and an int". Both are passed in directly, and the function doesn't change the grid.
    • No nested if for rows. The if sits inside the inner loop only, so it runs once per cell.

    Edge cases and common mistakes

    • No match. If the loops finish and nothing was counted, the function returns 0, as for [[7, 8, 9]] with target 4.
    • Negative targets. -1 is compared like any other integer. In [[-1, 5], [5, -1]] both -1 cells are counted.
    • Several matches in one row. The third row of the first example has two 2s, and both are counted. Stopping at the first match in a row would give 3 instead of 4.
    • Returning inside the loops. A return count in the loop would stop after the first cell, so the function would give a count for only a part of the grid.
    • Counting rows instead of cells. Adding 1 once per row that contains the target would also give 3 for the first example. The lesson counts cells.

    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 Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free