Start learning free

LESSON 257 OF 285 · NESTED LOOPS OVER GRIDS

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

    JAVASCRIPT · NESTED LOOPS OVER GRIDS

    Find In Grid in JavaScript, explained

    Problem overview

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

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

    Approach

    The answer is a position, so the loops must know where they are. That rules out for...of, which gives values only. Use index loops instead: the outer one over row numbers, the inner one over column numbers. An inner loop that finishes a whole row before the outer loop moves down is exactly reading order, so the first match the loops meet is the first one the problem asks for.

    When the check succeeds, return [row, col] immediately. There is no need to look at any other cell. If both loops end without a match, the target isn't in the grid, and the function returns [-1, -1]. Since -1 is never a real row or column number, a caller can tell the two cases apart.

    Step by step

    1. Loop over row numbers. for (let row = 0; row < grid.length; row++). grid.length is the number of rows, because the grid is an array of rows.
    2. Loop over column numbers inside it: for (let col = 0; col < grid[row].length; col++). grid[row] is one row, itself an array, so its length is the number of columns.
    3. Compare the cell. If grid[row][col] === target, return [row, col]. A return leaves the whole function, so both loops stop at the first match.
    4. Return [-1, -1] after both loops. The function only gets there when no cell matched.

    The solution in JavaScript

    class Solution {
        findInGrid(grid, target) {
            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];
        }
    }
    

    Details worth knowing:

    • return versus break. A break leaves only the inner loop. The outer loop would go on to the next row and might find a later match. return ends everything at once.
    • Returning an array. [row, col] builds a new two-element array, in that order: row first.
    • grid[row].length per row. It uses the current row's own length, which works even if rows were uneven. In this lesson all rows have the same length.
    • === compares without converting types, so the number 6 never matches the string "6".

    Complexity

    Time: O(r × c) in the worst case, when the target is in the last cell or missing. If the target is near the top left, the function stops much earlier.

    Space: O(1). The result is always two numbers.

    Edge cases and common mistakes

    • Several matches. Only the first counts. With [[5, 1], [1, 5]] and target 1 the function returns [0, 1]. Using break in place of return, and saving the position in a variable, would overwrite it with a later match and return [1, 0].
    • Swapped order. The result is [row, col], not [col, row]. For 6 in the first example, [1, 2] is right and [2, 1] points at the 8.
    • No match. [-1, -1] must be returned after the loops. Returning it inside a loop would end the search after the first cell.
    • Target at the corners. The first cell gives [0, 0], and the last cell gives the last row and column.
    • Mixing up the lengths. Rows are counted by grid.length, and columns by grid[row].length.

    Testing

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