Start learning free

LESSON 264 OF 293 · NESTED LOOPS OVER GRIDS

Find in a Grid in Rust: 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 Vec 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

    RUST · NESTED LOOPS OVER GRIDS

    Find In Grid in Rust, explained

    Problem overview

    find_in_grid receives a grid, a Vec<Vec<i32>> of rows, and an i32 target. It returns the position of the first cell equal to target as a vector of two integers: the row and the column, both counted from 0. "First" means reading order: the top row from left to right, then the next row, and so on. If no cell matches, the answer is [-1, -1]. In the grid [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the target 6 is in row 1, column 2, so the answer is [1, 2]. In [[5, 1], [1, 5]] the target 1 appears twice, and the one in row 0, column 1 comes first: [0, 1].

    Approach: loop by index and stop at the first match

    The answer is a position, so the loops need the row and column numbers, not just the values. That is why both loops run over index ranges. Going row by row and left to right inside each row is exactly reading order, so the first match found is the one the problem wants, and the function can return at once.

    Step by step

    1. Loop over row numbers. for row in 0..grid.len(). The length of the grid is the number of rows.
    2. Loop over column numbers. for col in 0..grid[row].len(). The length of the current row is the number of columns. The inner loop finishes a row before the next one starts.
    3. Test the cell. If grid[row][col] == target, return vec![row as i32, col as i32]. The return leaves the whole function, so both loops stop at the first match.
    4. Return the not-found answer. After both loops, vec![-1, -1]. The function only reaches this line when nothing matched, and -1 is never a real row or column.

    The solution in Rust

    impl Solution {
        fn find_in_grid(grid: Vec<Vec<i32>>, target: i32) -> Vec<i32> {
            for row in 0..grid.len() {
                for col in 0..grid[row].len() {
                    if grid[row][col] == target {
                        return vec![row as i32, col as i32];
                    }
                }
            }
            return vec![-1, -1];
        }
    }
    

    Rust details worth knowing:

    • usize to i32. The loop variables are usize, the type of vector indices, but the function returns a Vec<i32>. Rust does not convert between integer types on its own: vec![row, col] fails with expected `i32`, found `usize`. The as i32 casts do the conversion, and they are safe for these small grids.
    • Why not usize for -1? A usize can't be negative, which is one reason the answer vector holds i32.
    • The vec! macro. vec![-1, -1] builds a vector with those two elements, and its type is Vec<i32> from the return type.
    • Early return. Inside nested loops, a return exits every level at once.

    Complexity

    Time: O(r * c) in the worst case, when the target is in the last cell or missing. It can finish sooner when a match is early. Space: O(1) apart from the two-element answer.

    Edge cases and common mistakes

    • Several matches. The reading-order loops guarantee the first one is returned. Looping over columns first and rows inside would return the first match in column order instead, which can differ.
    • Row and column swapped. The answer is [row, col]. For target 6 in the first example, [2, 1] would be wrong.
    • No match. The loops end and the function returns [-1, -1].
    • The first and last cells. [[9]] with target 9 gives [0, 0], and the target 4 in [[1, 2], [3, 4]] gives [1, 1].
    • Returning [-1, -1] inside the loop. It would give up after the first cell that does not match.

    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].
    • [[9]] with target = 9 gives [0, 0].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free