Problem overview
Given a grid of integers and an integer target, return how many cells equal target. The grid is an Array<IntArray>: an array of rows, each row an array of integers. Values and the target can be negative.
In the grid with rows [1, 2, 3], [4, 2, 6] and [2, 8, 2], the target 2 appears once in the first row, once in the second and twice in the third, so the answer is 4. In the grid [-1, 5], [5, -1] with target -1 the answer is 2, because the two cells are in different rows and each counts. The single row [7, 8, 9] with target 4 gives 0.
Approach
You have to look at every cell, because any of them could match. Nested loops do that: the outer loop takes each row, the inner loop takes each value of the row, and a counter goes up for every value equal to target.
Step by step
- Create
var count = 0. It is avarbecause it increases inside the loops. - Write
for (row in grid). Eachrowis anIntArray. - Inside it, write
for (value in row). The inner loop finishes a whole row before the outer loop moves on, so every cell is visited exactly once. - If
value == target, docount++. Other cells are skipped. - After both loops,
return count. A return inside the loops would stop the search early.
The solution in Kotlin
class Solution {
fun countInGrid(grid: Array<IntArray>, target: Int): Int {
var count = 0
for (row in grid) {
for (value in row) {
if (value == target) {
count++
}
}
}
return count
}
}
Some Kotlin details:
==compares values in Kotlin. ForIntthat is exactly what you want:value == targetis true when the two numbers are equal.count++increments avar. Declaringcountwithvalwould give a compile error.- Function parameters such as
targetare read-only: you can use them but not assign to them. - The nested
foroverArray<IntArray>needs no indexes, because only the values matter. When you need the row and column numbers, as in finding a position, loop overgrid.indicesinstead.
Complexity
Every cell is checked once, so for r rows and c columns the time is O(r · c). The only extra storage is the counter, so the space is O(1).
Edge cases and common mistakes
- Stopping at the first match. This lesson counts all matches, so there is no early
return. - Counting rows instead of cells. A row with two matches adds 2, not 1. In the first example the third row adds 2.
- Negative targets. They need no special handling: -1 equals -1.
- No match. The counter stays at 0 and the function returns 0.
- Counter in the wrong place. Declaring
countinside a loop resets it, and you would return the count of the last row only, or fail to compile when it is used after the loop.
Testing
- Rows
[1, 2, 3],[4, 2, 6],[2, 8, 2]with target 2 give 4. - Rows
[-1, 5],[5, -1]with target -1 give 2. - The row
[7, 8, 9]with target 4 gives 0.
