Start learning free

LESSON 259 OF 291 · NESTED LOOPS OVER GRIDS

Column Sums in Scala: Looping by Index over a Grid

Practice Read the full explanation

Given a grid of integers grid, return an ArrayBuffer with the sum of each column, from left to right.

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.

Column c is made of the value at position c in every row.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: [5, 7, 9]
Explanation: Column 0 holds 1 and 4, column 1 holds 2 and 5, and column 2 holds 3 and 6: 1 + 4 = 5, 2 + 5 = 7 and 3 + 6 = 9.

Example 2:

Input: grid = [[2, -1],
               [3, -1],
               [-5, 7]]
Output: [0, 5]
Explanation: Column 0 is 2 + 3 + (-5) = 0 and column 1 is -1 + (-1) + 7 = 5.

Example 3:

Input: grid = [[4, -2, 9]]
Output: [4, -2, 9]
Explanation: With one row, every column holds a single number, so each column's sum is that 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 7
    Ctrl + Enter to check

    SCALA · NESTED LOOPS OVER GRIDS

    Column Sums in Scala, explained

    Problem overview

    The method columnSums receives grid, an Array[Array[Int]], and returns an ArrayBuffer[Int] with the sum of each column, from left to right. Column c is made of the value at position c in every row.

    For the rows [1, 2, 3] and [4, 5, 6], column 0 holds 1 and 4, column 1 holds 2 and 5, and column 2 holds 3 and 6, so the result is ArrayBuffer(5, 7, 9). For [2, -1], [3, -1] and [-5, 7] the result is ArrayBuffer(0, 5). With a single row, [4, -2, 9], each column holds one number, so the result is ArrayBuffer(4, -2, 9).

    Approach: columns on the outside, rows on the inside

    A grid is stored as a list of rows, so a column isn't an object you can loop over directly. Instead, pick a column number and visit that position in every row. That means looping over indexes, not over elements:

    • the outer loop goes through the column numbers, left to right;
    • for each column, a new total starts at 0 and the inner loop goes through the row numbers, adding grid(row)(col);
    • the finished total is appended to the result.

    Compared with the row-sum idea, the loops swap roles. The outer loop picks the column, so the sums come out in column order.

    Step by step

    1. Create the empty buffer val sums = ArrayBuffer[Int]().
    2. Loop over the column numbers with for (col <- grid(0).indices). All rows have the same length, so the indices of the first row are the column numbers.
    3. Create var total = 0 inside the loop. It starts again for every column.
    4. Loop over the row numbers with for (row <- grid.indices), inside the outer loop. A column has one number in each row.
    5. Add grid(row)(col) to total. grid(row) is a whole row, and (col) picks this column's number from it.
    6. Append total to sums after the inner loop, still inside the outer one.
    7. Return sums after both loops.

    The solution in Scala

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

    Scala details worth knowing:

    • Indexing uses parentheses. Scala reads an element with grid(row), not grid[row]; square brackets are for types. grid(row)(col) is two lookups in a row: first the row, then the element in it.
    • indices. grid.indices is the range 0 until grid.length, so it goes from 0 to the last valid index with no off-by-one risk.
    • Out-of-range indexes throw. Reading grid(row)(col) with a bad index throws an IndexOutOfBoundsException instead of reading neighbouring memory. Building the loops from indices keeps the indexes valid.
    • Empty grids. grid(0) fails on an array with no rows. The constraints guarantee at least one row, so the lesson doesn't need a guard.

    Complexity

    With R rows and C columns, the inner body runs R times for each of the C columns, so the time is O(R * C). The result has C entries, so the extra space is O(C).

    Edge cases and common mistakes

    • Swapping the indexes. Writing grid(col)(row) reads the grid transposed. On a grid with 2 rows and 3 columns it would try to read row 2, which doesn't exist, and throw.
    • Using the row count for the columns. The outer loop must run over grid(0).indices. With grid.indices, a grid that isn't square gets either too few sums or an exception from an index past the end of a row.
    • Creating total outside the outer loop. The sums would carry over from column to column.
    • Returning inside the outer loop. Only the first column's sum would come back.
    • One row. [[4, -2, 9]] works: each inner loop runs once and the sums are the values themselves.

    Testing

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