Start learning free

LESSON 261 OF 285 · NESTED LOOPS OVER GRIDS

Find in Grid in Go: First Match in Reading Order

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 a slice 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

    GO · NESTED LOOPS OVER GRIDS

    Find In Grid in Go, explained

    Problem overview

    The function findInGrid receives a grid, grid of type [][]int, and an integer target. It returns the position of the first cell equal to target as a slice of two integers, the row and then the column. Rows are numbered from 0 at the top and columns from 0 on the left. "First" means reading order: the top row from left to right, then the next row, and so on. When no cell matches, it returns [-1, -1].

    For [[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 the answer is [0 1], because the 1 in row 0 comes before the one in row 1. For a grid of 4s and target = 3 the answer is [-1 -1].

    Approach: scan in reading order and stop at the first hit

    A position needs two numbers, so this time the loops must give indexes, not copies of values. The outer loop goes over the row numbers and the inner loop over the column numbers of that row. Scanning rows top to bottom and each row left to right is exactly reading order, so the first match found is the one the problem asks for, and the function can return it immediately.

    If both loops end without a match, the target is not in the grid, and the function returns [-1, -1]. Since -1 is never a real row or column number, the learner and the tests can tell "not found" from any valid position.

    Step by step

    1. Loop over the row numbers: for row := range grid. With one variable, range gives the indexes 0, 1, 2 and so on, one per row.
    2. Loop over the column numbers of that row: for col := range grid[row]. grid[row] is the row itself, a []int, so its indexes are the column numbers.
    3. Test the cell: if grid[row][col] == target, return []int{row, col}. A return leaves the whole function, so both loops stop at the first match.
    4. After both loops, return []int{-1, -1}. The function only gets there when nothing matched.

    The solution in Go

    func findInGrid(grid [][]int, target int) []int {
        for row := range grid {
            for col := range grid[row] {
                if grid[row][col] == target {
                    return []int{row, col}
                }
            }
        }
        return []int{-1, -1}
    }
    

    Go details:

    • range with one variable gives indexes for a slice, not values. With two variables, as in for i, v := range s, it gives index and value.
    • A slice literal builds the answer. []int{row, col} creates a new two-element slice holding the row and the column, and the return type []int matches it.
    • break only leaves one loop. It would end the inner loop, and the outer loop would carry on with the next row. return ends the function, which is why it is the right tool here.
    • Printing. A returned []int{1, 2} prints as [1 2].

    Edge cases and common mistakes

    • Using break instead of return. A version that saves the position in a variable and calls break leaves only the inner loop, so later rows can overwrite the result. On [[5, 1], [1, 5]] with target 1, such a version returns [1 0] instead of [0 1].
    • Swapping row and column. The answer is row first, then column. For target 6 in the first example, [2 1] would be wrong.
    • Several matches. Only the first in reading order counts, and the early return guarantees it.
    • No match. Returning [0, 0] or an empty slice would be wrong, since [0, 0] is a real position. The lesson asks for [-1, -1].
    • Returning inside the wrong place. The final return []int{-1, -1} must come after the outer loop. Placed inside it, the function would give up after the first row.

    Testing

    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] with target = 6 gives [1 2].
    • [[5, 1], [1, 5]] with target = 1 gives [0 1].
    • [[4, 4], [4, 4]] with target = 3 gives [-1 -1].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free