Start learning free

LESSON 258 OF 291 · NESTED LOOPS OVER GRIDS

Row Sums in Scala: Nested Loops and ArrayBuffer

Practice Read the full explanation

Given a grid of integers grid, return an ArrayBuffer with the sum of each row, in the same order as the rows.

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: [6, 15]
Explanation: Row 0 adds up to 1 + 2 + 3 = 6 and row 1 to 4 + 5 + 6 = 15.

Example 2:

Input: grid = [[-1, -2],
               [-3, -4],
               [5, 5]]
Output: [-3, -7, 10]
Explanation: One sum per row, top to bottom. A row of negative numbers has a negative sum.

Example 3:

Input: grid = [[3],
               [1],
               [4]]
Output: [3, 1, 4]
Explanation: Every row has a single value, so each row's sum is that value.

 

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 7
    Ctrl + Enter to check

    SCALA · NESTED LOOPS OVER GRIDS

    Row Sums in Scala, explained

    Problem overview

    The method rowSums receives grid, an Array[Array[Int]], and returns an ArrayBuffer[Int] holding the sum of each row, in the same order as the rows. Every row has the same number of values.

    For the rows [1, 2, 3] and [4, 5, 6] the result is ArrayBuffer(6, 15). For [-1, -2], [-3, -4] and [5, 5] it is ArrayBuffer(-3, -7, 10): one sum per row, and a row of negative numbers has a negative sum. When every row holds one value, as in [3], [1], [4], each row's sum is that value.

    Approach: a fresh total for every row

    Summing the whole grid needs one running total. Here the answer is one sum per row, so each row needs its own total. The plan has two levels:

    • the outer loop picks a row;
    • for that row, a new total starts at 0, the inner loop adds up the row's values, and the finished total is appended to the result.

    Where the total is created is the whole point. Created inside the outer loop, it restarts at 0 for each row, so one row's numbers never leak into the next sum. Appending at the end of each pass keeps the sums in row order.

    Step by step

    1. Create the result buffer. val sums = ArrayBuffer[Int]() starts empty and collects one sum per row.
    2. Loop over the rows with for (row <- grid). It runs once per row, and each row is an Array[Int].
    3. Create var total = 0 inside that loop. It holds this row's sum and starts over for every row.
    4. Loop over the values of the row with for (value <- row), inside the outer loop.
    5. Add value to total in the inner loop.
    6. Append total to sums with +=, after the inner loop but still inside the outer one. At that point the whole row has been added.
    7. Return sums after the outer loop, not inside it, or only the first row's sum would come back.

    The solution in Scala

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

    Scala details worth knowing:

    • ArrayBuffer grows, Array doesn't. An Array has a fixed length, while ArrayBuffer from scala.collection.mutable can take new elements with +=. The lesson's code already has it imported; in a file of your own, add import scala.collection.mutable.ArrayBuffer.
    • val sums with a growing buffer. val fixes which buffer the name refers to, not what is inside it.
    • var total is local to one pass. A variable declared inside a loop body exists only during that pass. Each pass creates a new total that starts at 0.
    • Printing. An ArrayBuffer prints as ArrayBuffer(6, 15).

    Complexity

    With R rows and C columns, every value is added once, so the time is O(R * C). The result holds one number per row, so the extra space is O(R), plus a single total at a time.

    Edge cases and common mistakes

    • Declaring total before the outer loop. The total would keep growing across rows, and the result for the example would be ArrayBuffer(6, 21) instead of ArrayBuffer(6, 15).
    • Appending inside the inner loop. That adds a partial sum after every value, so the buffer gets one entry per cell.
    • Returning inside the outer loop. The method ends after the first row.
    • A single row or single column. Both work: [[3], [1], [4]] gives ArrayBuffer(3, 1, 4), because each inner loop runs once.
    • Negative numbers. They reduce the sum; no special handling is needed.

    Testing

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