Problem overview
Given a grid grid of type int[][] and an integer target, findInGrid finds the first cell equal to target and returns its position as a list of two integers: its row and then its column. Rows are numbered from 0 from the top, and columns from 0 from the left. "First" means in reading order: the top row from left to right, then the next row, and so on. If no cell matches, the method returns [-1, -1].
For the grid [[1, 2, 3], [4, 5, 6], [7, 8, 9]] and target = 6, the answer is [1, 2]: row 1, column 2. For [[5, 1], [1, 5]] and target = 1 there are two 1s, and the one in row 0, column 1 comes first, so the answer is [0, 1]. For [[4, 4], [4, 4]] and target = 3 it is [-1, -1].
Approach
To report a position, the code has to know the row number and the column number of every cell it looks at. A for-each loop doesn't provide them, so this lesson uses ordinary for loops with index variables row and col. The outer loop runs through the row numbers. For each row, the inner loop runs through the column numbers from left to right. That nesting visits cells in exactly the reading order the problem asks for.
The search can stop at the first match, so the method returns from inside the loops as soon as it finds one. If both loops finish, no cell matched, and the method returns the "not found" answer.
Step by step
- Write a
forloop with anintrowfrom 0 whilerow < grid.length. Since anint[][]is an array of rows,grid.lengthis the number of rows. - Inside it, write a
forloop with anintcolfrom 0 whilecol < grid[row].length. The expressiongrid[row]is that row, anint[], and its length is the number of columns. The inner loop finishes a whole row, left to right, before the next row starts. - Inside the inner loop, if
grid[row][col] == target, return a newArrayListholdingrowandcol, created withnew ArrayList<>(List.of(row, col)). Areturnleaves the whole method, so both loops stop at the first match. Abreakwould stop only the inner loop. - After both loops, return
new ArrayList<>(List.of(-1, -1)). The method gets here only when nothing matched, and -1 is never a real row or column number.
Tracing the second example
For [[5, 1], [1, 5]] and target = 1, the loops check grid[0][0] (5), then grid[0][1] (1). That matches, so the method returns [0, 1] at once. The 1 at grid[1][0] is never examined.
The solution in Java
class Solution {
public List<Integer> findInGrid(int[][] grid, int target) {
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
if (grid[row][col] == target) {
return new ArrayList<>(List.of(row, col));
}
}
}
return new ArrayList<>(List.of(-1, -1));
}
}
Java details in this code:
List.ofand why it is wrapped.List.of(row, col)makes a fixed list that can't be changed: callingaddon it throwsUnsupportedOperationException. Passing it tonew ArrayList<>(...)copies the two values into a regular, modifiableArrayList, which is what the lesson asks for.- Autoboxing.
rowandcolareintvalues, and the list holdsIntegerobjects. Java converts them for you inList.of(row, col). - Return type. Both
returnstatements produce anArrayList<Integer>, which is aList<Integer>, matching the method's declared type. The<>lets Java work out the element type from the declared type. - The imports.
ListandArrayListare injava.util, so a standalone program needsimport java.util.*;. - Index order.
grid[row][col]reads the row first, and the answer lists the row first, too.
Complexity
In the worst case, the target is the last cell or is missing, and every cell is checked once: O(R * C) time for R rows and C columns. The method uses only a few variables and a two-element result, so its extra space is O(1).
Edge cases and common mistakes
- Target not found. The return after the loops handles it. For
[[4, 4], [4, 4]]andtarget = 3, the method returns[-1, -1]. - Duplicates. Because the method returns at the first match in reading order, the answer for
[[5, 1], [1, 5]]andtarget = 1is[0, 1], not[1, 0]. - Using
breakinstead ofreturn. Abreakleaves only the inner loop, so the outer loop would go on to later rows and might find another match. - Returning
[col, row]. The task wants the row first. - Returning the
-1answer inside the loop. It belongs after both loops. Inside, it would be returned after the first cell that doesn't match. - Using the cell's value. The result is a position, not
target, which the caller already knows.
Testing
findInGrid(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 6)returns[1, 2].findInGrid(new int[][]{{5, 1}, {1, 5}}, 1)returns[0, 1].findInGrid(new int[][]{{4, 4}, {4, 4}}, 3)returns[-1, -1].
