Start learning free

LESSON 261 OF 291 · NESTED LOOPS OVER GRIDS

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

    SCALA · NESTED LOOPS OVER GRIDS

    Find In Grid in Scala, explained

    Problem overview

    The method findInGrid receives grid, an Array[Array[Int]], and an integer target. It returns the position of the first cell equal to target as an ArrayBuffer[Int] of two numbers: the row and the column. Both are counted from 0, rows from the top and columns from the left. If no cell matches, it returns ArrayBuffer(-1, -1).

    "First" means reading order: the top row from left to right, then the next row, and so on. For the grid with rows [1, 2, 3], [4, 5, 6] and [7, 8, 9] and target = 6, the answer is ArrayBuffer(1, 2): row 1, column 2. For [5, 1] and [1, 5] with target = 1, the 1 appears twice, and the answer is ArrayBuffer(0, 1), because the one in row 0 comes first. For a grid of 4s with target = 3 the answer is ArrayBuffer(-1, -1).

    Approach: scan in order and stop at the first hit

    The answer is a position, so the loops must work with row and column numbers, not just the values. An outer loop goes through the row numbers from the top, and an inner loop goes through the column numbers from the left. That nesting is exactly reading order: the inner loop finishes a whole row before the outer loop moves on.

    The first match found is the right one, so the method returns it immediately. Returning from inside the loops ends everything at once, which is what "first" needs. The fallback value is returned only after both loops have finished without a match.

    Step by step

    1. Loop over the row numbers with for (row <- grid.indices). The indices are 0, 1, 2 and so on, one per row, from the top.
    2. Loop over the column numbers of this row with for (col <- grid(row).indices). grid(row) is one row, an Array[Int], and its indices are the column numbers.
    3. Compare and return. If grid(row)(col) == target, return ArrayBuffer(row, col) right away. return leaves the whole method, so both loops stop at the first match.
    4. Return ArrayBuffer(-1, -1) after both loops. The method reaches this line only when nothing matched. -1 can't be a real row or column, so it is safe as a "not found" marker.

    The solution in Scala

    class Solution {
        def findInGrid(grid: Array[Array[Int]], target: Int): ArrayBuffer[Int] = {
            for (row <- grid.indices) {
                for (col <- grid(row).indices) {
                    if (grid(row)(col) == target) {
                        return ArrayBuffer(row, col)
                    }
                }
            }
            return ArrayBuffer(-1, -1)
        }
    }
    

    Scala details worth knowing:

    • Scala has no break keyword. A return is the simple way to leave nested loops early. In languages that do have break, it only leaves the innermost loop, so extra bookkeeping is needed for two levels.
    • return inside a for. A for over a range becomes a call that takes a function, and this return leaves the whole method from inside it. Scala 3.5 runs it correctly, with a warning that such non-local returns are no longer supported (it suggests scala.util.boundary).
    • ArrayBuffer(row, col) builds a buffer from its arguments. The lesson's code already imports ArrayBuffer; in a file of your own, add import scala.collection.mutable.ArrayBuffer.
    • Parentheses for indexing. grid(row)(col) reads the row, then the cell in that row.

    Complexity

    With R rows and C columns, the worst case, a target in the last cell or not present at all, checks every cell: O(R * C) time. A target near the top-left returns early. The extra space is O(1), because the result always has exactly two numbers.

    Edge cases and common mistakes

    • Several matches. Only the first in reading order is returned. For [[5, 1], [1, 5]] and target 1 the answer is ArrayBuffer(0, 1), not ArrayBuffer(1, 0).
    • The first and last cells. In the 3 by 3 grid above, target 1 gives ArrayBuffer(0, 0) and target 9 gives ArrayBuffer(2, 2).
    • Row and column swapped. The answer is (row, col). Returning ArrayBuffer(col, row) would give (2, 1) for the first example.
    • Returning (-1, -1) inside the loop. It must come after both loops. Inside, it would be returned as soon as the first cell fails to match.
    • Looping over values. for (value <- row) gives the value but not its column number. Loop over indices when the position is the answer.

    Testing

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