Start learning free

LESSON 261 OF 289 · NESTED LOOPS OVER GRIDS

Find in a Grid in TypeScript: 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 array 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

    TYPESCRIPT · NESTED LOOPS OVER GRIDS

    Find In Grid in TypeScript, explained

    Problem overview

    The method findInGrid receives a grid of integers (an array of rows) and an integer target. It returns the position of the first cell equal to target as an array 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, and so on. If nothing matches, the result is [-1, -1].

    In the grid [[1, 2, 3], [4, 5, 6], [7, 8, 9]], the target 6 is at row 1, column 2, so the result is [1, 2]. In [[5, 1], [1, 5]] the target 1 appears twice, and the one in row 0 comes first, so the result is [0, 1]. In [[4, 4], [4, 4]] the target 3 is missing and the result is [-1, -1].

    Approach: loop over positions and return at the first match

    Counting or summing only needs the values. This problem needs to report where a value is, so the loops run over row numbers and column numbers, not over the values. The outer loop goes through the rows from the top, and the inner loop through the columns of that row from the left. That nesting visits the cells in exactly reading order, so the first match found is the first one that counts.

    On a match, the function returns [row, col] immediately. A return leaves the whole function, so both loops stop. If both loops finish without a match, the code after them returns [-1, -1].

    Step by step

    1. Loop over the row numbers: for (let row = 0; row < grid.length; row++). The grid is an array of rows, so grid.length is the number of rows.
    2. Loop over the column numbers inside it: for (let col = 0; col < grid[row].length; col++). grid[row] is one row, itself an array, and its length is the number of columns.
    3. Compare. If grid[row][col] === target, return [row, col] right away. A break would only leave the inner loop, so the search would go on in the next row.
    4. Return [-1, -1] after both loops. The function reaches this line only if no cell matched. -1 is never a real row or column, so it signals "not found".

    The solution in TypeScript

    class Solution {
        findInGrid(grid: number[][], target: number): number[] {
            for (let row = 0; row < grid.length; row++) {
                for (let col = 0; col < grid[row].length; col++) {
                    if (grid[row][col] === target) {
                        return [row, col];
                    }
                }
            }
            return [-1, -1];
        }
    }
    

    Language details worth knowing:

    • Index loops instead of for...of. for...of gives values, not positions. When the answer includes positions, counting loops with let row = 0 and let col = 0 are the simple choice.
    • Returning an array. [row, col] is an array literal, which matches the declared return type number[].
    • grid[row].length. Using the current row's length for the inner bound works for any row, even if rows had different lengths.
    • Types are erased. The annotations check nothing at run time, but the returned array holds numbers because row and col are numbers.

    Complexity

    Time: O(R * C) in the worst case, when the target is in the last cell or absent. It can stop much sooner when the first match is near the top. Space: O(1) besides the two-element result.

    Edge cases and common mistakes

    • Several matches. The first in reading order wins. findInGrid([[5, 1], [1, 5]], 1) returns [0, 1], not [1, 0].
    • Match in the top-left corner. [0, 0] is a real answer, which is why "not found" uses -1 and not 0.
    • Row and column swapped. The result is row first. In the first example, [2, 1] would point at the 8.
    • Using break. It ends only the inner loop. The outer loop would continue and could return a later match, or the wrong position.
    • Returning [-1, -1] inside a loop. It would end the search after the first cell. The not-found answer belongs after both loops.

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