Start learning free

LESSON 256 OF 281 · NESTED LOOPS OVER GRIDS

Find in Grid in C++: 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 vector of two integers: its row and its column.

A grid is a vector of rows, and each row is a vector 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

    C++ · NESTED LOOPS OVER GRIDS

    Find In Grid in C++, explained

    Problem overview

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

    In [[1, 2, 3], [4, 5, 6], [7, 8, 9]] with target = 6, the answer is [1, 2]: row 1, column 2. In [[5, 1], [1, 5]] with target = 1, the value appears twice, and the answer is [0, 1] because that cell comes first in reading order. In [[4, 4], [4, 4]] with target = 3 the answer is [-1, -1].

    Approach: loop with indices, return at the first match

    The function must report a position, so it needs the row and column numbers and not only the values. That means index-based loops: an outer loop over row, and an inner loop over col. Going through the columns of a row from left to right before moving to the next row is exactly the reading order the problem asks for, so the first match the loops meet is the right one.

    When a cell matches, the function returns at once. A return leaves the whole function, so both loops stop. After the loops, the function knows that no cell matched, and it returns the sentinel [-1, -1]. No real position has a negative number, so the caller can tell it apart from a find.

    Step by step

    1. Loop over the row numbers. Use an int named row from 0 while row < grid.size(). The grid is a vector of rows, so grid.size() is the number of rows.
    2. Loop over the column numbers of this row. Use an int named col from 0 while col < grid[row].size(). grid[row] is one row, and its size is the number of columns.
    3. Compare the cell with the target. If grid[row][col] == target, return {row, col}. The braces build the vector<int> from the two numbers.
    4. Return {-1, -1} after both loops. This line is reached only when nothing matched.

    The solution in C++

    class Solution {
    public:
        vector<int> findInGrid(vector<vector<int>> &grid, int target) {
            for (int row = 0; row < grid.size(); row++) {
                for (int col = 0; col < grid[row].size(); col++) {
                    if (grid[row][col] == target) {
                        return {row, col};
                    }
                }
            }
            return {-1, -1};
        }
    };
    

    C++ details:

    • Returning a braced list. return {row, col}; creates the returned vector<int> directly from two int values. The function's return type tells the compiler what the braces mean.
    • return versus break. A break would stop only the inner loop, and the outer loop would carry on to the next row. A return ends the function, which is what a "first match" search needs.
    • Indices instead of range loops. A range-based loop gives values, not positions. When the answer includes a position, the loop variables must be the indices.
    • Unsigned sizes. grid.size() is unsigned and row is an int. The comparison works for these small sizes, though compilers may warn about it.

    Complexity

    In the worst case, when the target is in the last cell or missing, the function checks every cell, so the time is O(R * C) for R rows and C columns. It can stop earlier when a match is found. The extra space is constant, since only two loop counters are used and the result has two numbers.

    Edge cases and common mistakes

    • Several matches. The first in reading order wins: [[5, 1], [1, 5]] with target 1 gives [0, 1], not [1, 0].
    • Swapped order. The row comes first in the answer. For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] with target 6, [1, 2] is correct and [2, 1] would point at 8.
    • Using break. After a break the function would continue searching the later rows, and could report a later match or [-1, -1].
    • Corners. The first cell, [0, 0], and the last cell, [2, 2] in a 3 by 3 grid, are found correctly.
    • All cells equal to the target. [[4, 4], [4, 4]] with target 4 returns [0, 0].

    Testing

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