Start learning free

LESSON 257 OF 285 · NESTED LOOPS OVER GRIDS

Find in a Grid in Java: Row and Column of the First Match

Practice Read the full explanation

Given a grid of integers grid and an integer target, find the first cell equal to target and return its position as an ArrayList of two integers: its row and its column.

A grid is an array of rows, and each row is an array of integers. Rows are numbered from 0, top to bottom, and columns from 0, left to right.

"First" means in reading order: the top row from left to right, then the next row, and so on. If no cell is equal to target, return [-1, -1].

 

Example 1:

Input: grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
], target = 6
Output: [1, 2]
Explanation: 6 is in row 1 (the second row) and column 2 (the third column).

Example 2:

Input: grid = [
  [5, 1],
  [1, 5]
], target = 1
Output: [0, 1]
Explanation: 1 appears twice. Reading row by row, the 1 in row 0, column 1 comes before the 1 in row 1, column 0.

Example 3:

Input: grid = [
  [4, 4],
  [4, 4]
], target = 3
Output: [-1, -1]
Explanation: No cell is equal to 3.

 

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 4
    Ctrl + Enter to check

    JAVA · NESTED LOOPS OVER GRIDS

    Find In Grid in Java, explained

    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

    1. Write a for loop with an int row from 0 while row < grid.length. Since an int[][] is an array of rows, grid.length is the number of rows.
    2. Inside it, write a for loop with an int col from 0 while col < grid[row].length. The expression grid[row] is that row, an int[], and its length is the number of columns. The inner loop finishes a whole row, left to right, before the next row starts.
    3. Inside the inner loop, if grid[row][col] == target, return a new ArrayList holding row and col, created with new ArrayList<>(List.of(row, col)). A return leaves the whole method, so both loops stop at the first match. A break would stop only the inner loop.
    4. 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.of and why it is wrapped. List.of(row, col) makes a fixed list that can't be changed: calling add on it throws UnsupportedOperationException. Passing it to new ArrayList<>(...) copies the two values into a regular, modifiable ArrayList, which is what the lesson asks for.
    • Autoboxing. row and col are int values, and the list holds Integer objects. Java converts them for you in List.of(row, col).
    • Return type. Both return statements produce an ArrayList<Integer>, which is a List<Integer>, matching the method's declared type. The <> lets Java work out the element type from the declared type.
    • The imports. List and ArrayList are in java.util, so a standalone program needs import 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]] and target = 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]] and target = 1 is [0, 1], not [1, 0].
    • Using break instead of return. A break leaves 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 -1 answer 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].
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free