Start learning free

LESSON 260 OF 291 · NESTED LOOPS OVER GRIDS

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

    SCALA · NESTED LOOPS OVER GRIDS

    Count In Grid in Scala, explained

    Problem overview

    The method countInGrid receives grid, an Array[Array[Int]], and an integer target. It returns 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.

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

    Approach: visit every cell once

    There is no shortcut: the target can be in any cell, so every cell has to be looked at. Two nested loops do that. The outer loop goes through the rows, and the inner loop goes through the values of each row. Every cell is visited exactly once, and a counter goes up whenever a value equals the target.

    This is the counting pattern from a flat array, with one more loop around it. The counter is created once, before both loops, because the answer covers the whole grid.

    Step by step

    1. Create var count = 0. It holds the number of matching cells found so far. It is a var, because it goes up inside the loops.
    2. Loop over the rows with for (row <- grid). Each row is an Array[Int].
    3. Loop over the values of the row with for (value <- row), inside the first loop. The whole row is visited before the next row starts.
    4. Compare and count. If value == target, add 1 to count with += 1. Cells with any other value change nothing.
    5. Return count after both loops, so every cell has been checked first.

    The solution in Scala

    class Solution {
        def countInGrid(grid: Array[Array[Int]], target: Int): Int = {
            var count = 0
            for (row <- grid) {
                for (value <- row) {
                    if (value == target) {
                        count += 1
                    }
                }
            }
            return count
        }
    }
    

    Scala details worth knowing:

    • == compares values. For integers, value == target is true when the numbers are equal. For other types, Scala's == also compares by value, not by reference.
    • var versus val. count += 1 is count = count + 1, which needs a var. Declaring count with val is a compile error.
    • Elements, not positions. Both loops give the elements directly, so no index arithmetic is needed. This lesson only asks how many cells match, not where they are.
    • Negative targets. Nothing special: -1 is an ordinary Int.

    Complexity

    With R rows and C columns, the comparison runs once per cell, so the time is O(R * C). The extra space is O(1): a counter and the loop variables.

    Edge cases and common mistakes

    • No match. The counter never changes and the method returns 0.
    • Every cell matches. For a grid of 2 rows and 3 columns filled with the target, the answer is 6.
    • Counting rows instead of cells. A row with two matches must add 2, not 1. The comparison is inside the inner loop for that reason.
    • Resetting the counter. Creating count inside the outer loop would keep only the last row's count.
    • Returning inside the loops. The method would stop before checking all the 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 Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free