Start learning free

LESSON 262 OF 292 · NESTED LOOPS OVER GRIDS

Find in a Grid in Swift: Early Return from Nested Loops

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

    SWIFT · NESTED LOOPS OVER GRIDS

    Find In Grid in Swift, explained

    Problem overview

    The method findInGrid receives grid, an array of rows of integers, and an integer target. It returns the position of the first cell equal to target as an array of two integers, its row and its 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 method returns [-1, -1].

    In [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the target 6 is in row 1 and 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 in reading order, so the answer is [0, 1]. In [[4, 4], [4, 4]] there is no 3, so the answer is [-1, -1].

    Approach

    The answer is a position, so the loops must know the row and column numbers, not just the values. That means looping over indexes: row numbers from 0 up to grid.count - 1, and for each row, column numbers from 0 up to that row's length minus one.

    Looping rows in the outer loop and columns in the inner loop gives reading order automatically. The inner loop goes through a whole row from left to right before the next row starts, so the first match the loops find is the first match in reading order. Then the method can stop at once and report it.

    If the loops end without a match, the target is not in the grid, and the fallback answer [-1, -1] is returned. The value -1 can never be a real row or column number, so it is safe as a "not found" marker.

    Step by step

    1. Loop over the row numbers. for row in 0..<grid.count. Since the grid is an array of rows, grid.count is the number of rows.
    2. Loop over the column numbers of this row. for col in 0..<grid[row].count goes inside. grid[row] is one row, so its count is the number of columns.
    3. Test the cell. If grid[row][col] == target, return [row, col] immediately.
    4. Return [-1, -1] after both loops. The method only gets there when nothing matched.

    The solution in Swift

    class Solution {
        func findInGrid(_ grid: [[Int]], _ target: Int) -> [Int] {
            for row in 0..<grid.count {
                for col in 0..<grid[row].count {
                    if grid[row][col] == target {
                        return [row, col]
                    }
                }
            }
            return [-1, -1]
        }
    }
    

    Swift details worth knowing:

    • return leaves the whole method. It stops both loops at the first match. A break would only leave the inner loop, and the outer loop would carry on to the next row, possibly finding a later match and returning that one instead.
    • Array literals as results. [row, col] builds a new [Int], which fits the declared return type.
    • 0..<n is half-open. It covers exactly the valid indexes of an array of n elements. Swift traps on any index outside the array, so an off-by-one such as 0...grid.count crashes the program.
    • Indexes only when needed. A plain for row in grid loop would not tell the method which row it is on, which is why this lesson loops over numbers.

    Complexity

    In the worst case, when the target is the last cell or missing, every cell is checked once, so time is O(r * c). A match near the top-left ends the search early. Space is O(1): the result array has two elements regardless of the grid's size.

    Edge cases and common mistakes

    • Several matches. The first one in reading order wins. For [[5, 1], [1, 5]] and target 1, the answer is [0, 1], not [1, 0].
    • No match. [[4, 4], [4, 4]] with target 3 returns [-1, -1].
    • Row and column swapped. The answer is [row, col]. For target 6 in the first example, [2, 1] would be a different cell.
    • Using break. It leaves only the inner loop, so the method would continue with later rows.
    • Returning the fallback too early. Writing return [-1, -1] inside a loop would report "not found" after checking one cell.
    • Negative targets. They are ordinary values and need no special handling.

    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 Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free