Problem overview
Given a grid grid of type int[][] and an integer target, countInGrid 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. Values and the target can be negative.
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 it is 2, because the two cells are in different rows and each one counts. For [[7, 8, 9]] and target = 4 it is 0.
Approach
This is the usual counting pattern, with a grid instead of a flat array: keep a counter, visit every item once, and add 1 whenever the item matches. Visiting every cell of an int[][] takes two loops, since the grid holds rows and each row holds values. The outer loop picks a row, and the inner loop goes through that whole row before the next row begins. Every cell is checked exactly once, and the order doesn't matter, since we only count matches.
Step by step
- Create an
intnamedcountstarting at 0. No cell has been checked yet, so no match has been found. - Write a for-each loop with an
int[]namedrowovergrid. Each item of anint[][]is a row, which is anint[]. - Inside it, write a for-each loop with an
intnamedvalueoverrow. - Inside the inner loop,
if (value == target), add 1 tocountwithcount++. Cells with any other value are skipped. - After both loops, return
count. Returning inside a loop would end the method before every cell was checked.
Tracing the first example
For the 3 by 3 grid and target = 2, the first row [1, 2, 3] has one 2, so count becomes 1. The second row [4, 2, 6] adds another, making 2. The third row [2, 8, 2] has two, bringing the count to 4. The method returns 4.
The solution in Java
class Solution {
public int countInGrid(int[][] grid, int target) {
int count = 0;
for (int[] row : grid) {
for (int value : row) {
if (value == target) {
count++;
}
}
}
return count;
}
}
Java details in this code:
==is right forint.valueandtargetare primitiveintvalues, so==compares the numbers. The rule that==on objects compares references applies toIntegerorString, not to primitives. If the grid heldIntegerobjects, you would useequals.- One equals sign or two.
value == targettests, andvalue = targetassigns. In anif, the assignment form doesn't compile forint, because the condition must be aboolean. - The outer loop variable is an array.
int[] rowrefers to a row inside the grid, not a copy. This code only reads it. - No position needed. The task asks only for how many cells match, not where they are, so for-each loops are enough. The next kind of task, finding a position, needs row and column numbers.
Edge cases and common mistakes
- No match. If nothing equals
target,countstays 0, which is the right answer. For[[7, 8, 9]]andtarget = 4, the method returns 0. - Several matches in one row. Every cell counts, including two equal cells next to each other. The inner loop adds to
countfor each one. - Negative targets.
-1is an ordinaryint, andvalue == targetworks the same way. For[[-1, 5], [5, -1]]andtarget = -1, the result is 2. - Counting rows instead of cells. Adding 1 once per row that contains the target would give 3 for the first example instead of 4. Count in the inner loop.
- Returning inside the loops. A
return count;placed in a loop would stop after the first row or the first cell.
Testing
countInGrid(new int[][]{{1, 2, 3}, {4, 2, 6}, {2, 8, 2}}, 2)returns 4.countInGrid(new int[][]{{-1, 5}, {5, -1}}, -1)returns 2.countInGrid(new int[][]{{7, 8, 9}}, 4)returns 0.
