Start learning free

LESSON 260 OF 289 · NESTED LOOPS OVER GRIDS

Count in a Grid in TypeScript: 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

    TYPESCRIPT · NESTED LOOPS OVER GRIDS

    Count In Grid in TypeScript, explained

    Problem overview

    The method countInGrid receives a grid of integers, an array of rows, and an integer target. It returns how many cells of the grid are equal to target. Values and the target can be negative.

    For a grid with rows [1, 2, 3], [4, 2, 6] and [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, and for [[7, 8, 9]] and target = 4 it is 0.

    Approach: visit every cell and count the matches

    There is no shortcut: the target can be in any cell, so every cell must be looked at. Two nested loops do it. The outer loop takes the rows one at a time, and the inner loop goes through the whole current row before the outer loop moves on. Each cell is visited exactly once, and a counter goes up by one for each cell that equals the target.

    The counter is created before the loops so it keeps its value from one cell to the next, and the function returns it after both loops, once every cell has been checked.

    Compared with finding a value, counting never stops early. A search can return at the first match, but a count has to see the last cell, because the last cell may be one more match. That is why the return sits after the loops and the loops have no break.

    Step by step

    1. Declare count with let and start it at 0. It is let, not const, because it changes inside the loops.
    2. Loop over the rows: for (const row of grid). A number[][] is an array of rows, so each row is a number[].
    3. Loop over the values of the row: for (const value of row), inside the first loop.
    4. Compare and count. If value === target, add 1 with count++. Other values are skipped.
    5. Return count after both loops.

    The solution in TypeScript

    class Solution {
        countInGrid(grid: number[][], target: number): number {
            let count = 0;
            for (const row of grid) {
                for (const value of row) {
                    if (value === target) {
                        count++;
                    }
                }
            }
            return count;
        }
    }
    

    Language details worth knowing:

    • ===. It compares two values without converting types. For numbers it is the right test for "equal". Negative numbers need nothing special: -1 === -1 is true.
    • count++. It adds 1 to count. It is shorthand for count += 1.
    • Inferred type. let count = 0 has the type number without an annotation, because the compiler infers it from the starting value.
    • Nested for...of. The loop variables row and value are declared with const: they are new on each pass and never reassigned.

    Complexity

    Time: O(R * C) for R rows and C columns, one comparison per cell. Space: O(1), a single counter.

    Edge cases and common mistakes

    • Matches in different rows. Every one counts. [[-1, 5], [5, -1]] with target -1 gives 2.
    • No match. The counter never moves, and the function returns 0.
    • Returning inside the loops. A return there would end the function at the first cell or the first row, before the count is complete.
    • Using const for the counter. Changing it later with count++ would be an error.
    • Stopping at the first match. This lesson counts every match. Finding only the first one is a different problem.

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