Start learning free

LESSON 257 OF 291 · NESTED LOOPS OVER GRIDS

Grid Sum in Scala: Nested for Loops

Practice Read the full explanation

Given a grid of integers grid, return the sum of all the numbers in it.

A grid is a table of numbers made of rows. Every row has the same number of values, one in each column. Rows are counted from the top and columns from the left, both starting at 0.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: 21
Explanation: The first row adds up to 1 + 2 + 3 = 6 and the second to 4 + 5 + 6 = 15. Together: 6 + 15 = 21.

Example 2:

Input: grid = [[-3, 4],
               [5, -6]]
Output: 0
Explanation: -3 + 4 + 5 + (-6) = 0. Negative numbers make the sum smaller.

Example 3:

Input: grid = [[7]]
Output: 7
Explanation: A grid with one row and one column holds a single number.

 

Constraints:

  • grid has at least 1 row and at most 10 rows.
  • Every row has the same number of values, at least 1 and at most 10.
  • Every value is an integer between -1000 and 1000.
STEP 1 OF 5
    Ctrl + Enter to check

    SCALA · NESTED LOOPS OVER GRIDS

    Grid Sum in Scala, explained

    Problem overview

    The method gridSum receives grid, an Array[Array[Int]], and returns the sum of every number in it. A grid is a table: an array of rows, each row an array of integers, and all rows have the same length.

    For the grid with rows [1, 2, 3] and [4, 5, 6] the first row adds up to 6 and the second to 15, so the answer is 21. For rows [-3, 4] and [5, -6] the answer is 0, since negative numbers simply make the sum smaller. A grid with one cell, [[7]], gives 7.

    Approach: one loop inside another

    Adding up a flat array takes one loop. A grid is an array of arrays, so it takes two. The outer loop visits the rows. For each row, the inner loop visits that row's values. Together they reach every cell exactly once, and each value is added to a running total.

    The order doesn't matter for a sum, so the loops can go row by row without any special care. What matters is where the total lives: it is created once, before both loops, so that numbers from every row pile up in the same variable.

    Step by step

    1. Create var total = 0. Nothing has been added yet, so the sum so far is 0. It is a var because it changes.
    2. Loop over the rows with for (row <- grid). Each element of an Array[Array[Int]] is an Array[Int], one row of the grid.
    3. Loop over the values of the row with for (value <- row), inside the first loop. For each row, it goes through every value before the outer loop moves to the next row.
    4. Add value to total inside the inner loop.
    5. Return total after both loops, once every cell has been added.

    The solution in Scala

    class Solution {
        def gridSum(grid: Array[Array[Int]]): Int = {
            var total = 0
            for (row <- grid) {
                for (value <- row) {
                    total += value
                }
            }
            return total
        }
    }
    

    Scala details worth knowing:

    • Array[Array[Int]]. The type is an array whose elements are themselves arrays of Int. Square brackets hold type parameters in Scala, not indexes.
    • Looping directly over elements. for (row <- grid) gives the rows themselves, not their positions, so there are no index variables and no off-by-one mistakes. When you need positions, for example to read a column or a diagonal, loop over grid.indices instead.
    • += on a var. total += value means total = total + value.
    • Int is 32 bits. Overflow wraps silently, but the constraints keep the sum tiny: at most 100 cells of at most 1000 each.

    Complexity

    With R rows and C columns, the inner body runs once per cell, so the time is O(R * C): the number of values in the grid, which every correct solution has to read. The extra space is O(1), just total and the loop variables.

    Edge cases and common mistakes

    • A single cell. [[7]] runs each loop once and returns 7.
    • Negative values. They are added like any other number: for [[-3, 4], [5, -6]] the result is 0.
    • Creating total inside the outer loop. It would reset to 0 for every row and the method would return only the last row's sum.
    • Returning inside a loop. The method would end after the first row or the first value, and part of the grid would never be added.
    • Declaring total with val. The compiler rejects total += value on a val.

    Testing

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