Start learning free

LESSON 261 OF 292 · NESTED LOOPS OVER GRIDS

Count in a Grid in Swift: Nested Loops

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

    SWIFT · NESTED LOOPS OVER GRIDS

    Count In Grid in Swift, explained

    Problem overview

    The method countInGrid receives grid, an array of rows of integers, and an integer target. It returns how many cells of the grid are equal to target. Values and target are between -1000 and 1000, so they can be negative. The grid has at least one row and one column.

    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, since the two cells with -1 are in different rows and each counts. For [[7, 8, 9]] and target = 4 nothing matches, so the answer is 0.

    Approach

    Every cell has to be looked at, so the method uses two loops: one over the rows and, inside it, one over the values of the current row. A counter starts at 0 and goes up by 1 each time a cell equals target.

    Because the type of grid is [[Int]], an array of [Int] rows, the outer loop's variable is a whole row and the inner loop's variable is a single number. The inner loop finishes a full row before the outer loop moves on, so each of the cells is visited exactly once. A cell counts regardless of where it sits: nothing about its row or column matters, only its value.

    Step by step

    1. Create count with var, starting at 0, because nothing has matched yet and the value will change.
    2. Loop over the rows. for row in grid picks one row at a time from the top.
    3. Loop over the row's values. for value in row goes inside the first loop.
    4. Compare and count. If value == target, add 1 with count += 1. Other values are skipped.
    5. Return count after both loops. Returning earlier would stop before every cell was checked.

    The solution in Swift

    class Solution {
        func countInGrid(_ grid: [[Int]], _ target: Int) -> Int {
            var count = 0
            for row in grid {
                for value in row {
                    if value == target {
                        count += 1
                    }
                }
            }
            return count
        }
    }
    

    Swift details worth knowing:

    • == compares values. For Int it is the ordinary equality test. A single = inside an if is an error in Swift, since assignment doesn't produce a Bool, so that classic slip does not compile.
    • Parameters are constants. target can be read but not changed inside the method, which is exactly what the comparison needs.
    • The signature. The underscores mean a call looks like countInGrid(grid, 2), with no argument labels.
    • Counting without an index. Looping over values directly means there is no index to go out of range. Indexes would be needed only if the answer had to say where the match is.

    Complexity

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

    Edge cases and common mistakes

    • No match. [[7, 8, 9]] with target 4 returns 0, because count never changes.
    • Several matches in one row. Each cell counts. The third row of the first example has two 2s and adds 2.
    • Negative targets. They work the same way: [[-1, 5], [5, -1]] with target -1 gives 2.
    • Returning inside the loop. It would end at the first match or after the first row. This lesson counts all matches; stopping at the first one is what a search does.
    • Counting rows instead of cells. Adding 1 once per row that contains the target would undercount rows that hold the target more than 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.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free