Start learning free

LESSON 263 OF 293 · NESTED LOOPS OVER GRIDS

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

    RUST · NESTED LOOPS OVER GRIDS

    Count In Grid in Rust, explained

    Problem overview

    count_in_grid receives a grid, a Vec<Vec<i32>> of rows, and an i32 target. It returns how many cells are equal to target. For the grid [[1, 2, 3], [4, 2, 6], [2, 8, 2]] and target = 2, the value 2 appears once in the first row, once in the second and twice in the third, so the answer is 4. For [[-1, 5], [5, -1]] with target = -1 the answer is 2, and for [[7, 8, 9]] with target = 4 it is 0.

    Approach: visit every cell and count the matches

    There is no shortcut: the grid is not sorted, so any cell can be a match and every one must be looked at. An outer loop goes through the rows and an inner loop through the values of the current row. Each value is compared with target, and a match adds 1 to a counter.

    Step by step

    1. Create the counter. let mut count = 0; holds the matches found so far. It is mut because it grows inside the loops.
    2. Loop over the rows. for row in &grid borrows each row, a Vec<i32>, without taking it out of the grid.
    3. Loop over the values of the row. for value in row goes through the whole row before the outer loop moves on, so every cell is visited exactly once.
    4. Compare. if *value == target checks the cell. On a match, count += 1.
    5. Return after the loops, when every cell has been checked.

    The solution in Rust

    impl Solution {
        fn count_in_grid(grid: Vec<Vec<i32>>, target: i32) -> i32 {
            let mut count = 0;
            for row in &grid {
                for value in row {
                    if *value == target {
                        count += 1;
                    }
                }
            }
            return count;
        }
    }
    

    Rust details worth knowing:

    • References and *. Because the loops borrow, value is a &i32, a reference to the number. target is an i32. Rust has no == between a reference and a plain number: value == target fails with can't compare `&{integer}` with `{integer}`. Writing *value reads the number the reference points to.
    • The type of count. It starts as a bare 0, and the return type makes it an i32.
    • No index arithmetic. Looping over the values themselves avoids indices, so there is no way to go out of bounds here.

    How the loops move

    For the first example the outer loop starts with the row [1, 2, 3], and the inner loop compares 1, 2 and 3 with the target 2, finding one match. Then the outer loop moves to [4, 2, 6] for one more, and finally to [2, 8, 2] for two. The counter goes 1, 2, 4, and that is the value returned. The counter belongs before the outer loop, so it keeps its value from one row to the next.

    Complexity

    Time: O(r * c) for r rows and c columns, because each cell is compared once. Space: O(1), since only count and the loop variables are stored.

    Edge cases and common mistakes

    • No match. The counter never changes and the function returns 0.
    • Every cell matches. For a 2 by 2 grid of 3s with target = 3 the answer is 4, one per cell.
    • Negative targets. They compare like any other number.
    • Stopping at the first match. A return inside the loop would make this a "does it exist" function. Counting needs the loops to finish.
    • Counting rows. A row that contains the target several times must add several times, not once.

    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.
    • [[3, 3], [3, 3]] with target = 3 gives 4.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free