Start learning free

LESSON 261 OF 291 · NESTED LOOPS OVER GRIDS

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

    KOTLIN · NESTED LOOPS OVER GRIDS

    Find In Grid in Kotlin, explained

    Problem overview

    Given a grid of integers (an Array<IntArray>) and a target, find the first cell equal to target and return its position as a list of two integers: 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 no cell matches, return [-1, -1].

    In the 3 by 3 grid of 1 to 9, the target 6 is in row 1, column 2, so the result is [1, 2]. For rows [5, 1] and [1, 5] with target 1, there are two matches. The one in row 0, column 1 comes first, so the result is [0, 1]. A grid of 4s with target 3 gives [-1, -1].

    Approach

    Search the cells in reading order and stop at the first match. Because the answer includes row and column numbers, the loops must run over indexes rather than values. The outer loop goes over the row numbers and the inner loop over the column numbers of that row. That order is exactly the reading order the problem asks for, so the first hit is the right one.

    Step by step

    1. Loop over the row numbers: for (row in grid.indices). grid.indices is 0, 1, 2 and so on, one per row.
    2. Inside it, loop over the column numbers of that row: for (col in grid[row].indices). grid[row] is one row, and its indices are the column numbers.
    3. If grid[row][col] == target, return mutableListOf(row, col) right away. A return leaves the whole function, so both loops stop at the first match.
    4. After both loops, return mutableListOf(-1, -1). The function only gets there when nothing matched, and -1 is never a real row or column number.

    The solution in Kotlin

    class Solution {
        fun findInGrid(grid: Array<IntArray>, target: Int): List<Int> {
            for (row in grid.indices) {
                for (col in grid[row].indices) {
                    if (grid[row][col] == target) {
                        return mutableListOf(row, col)
                    }
                }
            }
            return mutableListOf(-1, -1)
        }
    }
    

    Some Kotlin details:

    • indices is a property of arrays and lists that gives the range of valid positions, 0 up to size - 1. It is the same as 0 until grid.size.
    • mutableListOf(row, col) builds a list of two Int values. The return type List<Int> accepts it, since a mutable list is a list.
    • A return inside nested loops leaves the function, not just the inner loop. A break would stop only the inner loop, and the outer loop would carry on to the next row.
    • Printing the result of the first example shows [1, 2].

    Complexity

    In the worst case, when there is no match or the match is in the last cell, every cell is checked once: O(r · c) time for r rows and c columns. The extra space is O(1), apart from the two-element result.

    Edge cases and common mistakes

    • Swapping row and column. The result is [row, col]. For the 1 to 9 grid and target 6, [2, 1] would point at 8.
    • Going column by column. Looping over columns in the outer loop finds matches in a different order. For rows [5, 1] and [1, 5] and target 1 it would find row 1, column 0 first, not [0, 1].
    • Using break. It stops one loop only, so the search goes on and a later match could replace the first.
    • Forgetting the not-found result. Without the final return, the function doesn't compile, since it must return on every path.

    Testing

    • The grid of 1 to 9 in three rows with target 6 gives [1, 2].
    • Rows [5, 1], [1, 5] with target 1 give [0, 1].
    • Rows [4, 4], [4, 4] with target 3 give [-1, -1].
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free