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
- Create the empty buffer
val sums = ArrayBuffer[Int](). - 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. - Create
var total = 0inside the loop. It starts again for every column. - Loop over the row numbers with
for (row <- grid.indices), inside the outer loop. A column has one number in each row. - Add
grid(row)(col)tototal.grid(row)is a whole row, and(col)picks this column's number from it. - Append
totaltosumsafter the inner loop, still inside the outer one. - Return
sumsafter 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), notgrid[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.indicesis the range0 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 anIndexOutOfBoundsExceptioninstead of reading neighbouring memory. Building the loops fromindiceskeeps 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. Withgrid.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
totaloutside 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]]givesArrayBuffer(5, 7, 9).[[2, -1], [3, -1], [-5, 7]]givesArrayBuffer(0, 5).[[4, -2, 9]]givesArrayBuffer(4, -2, 9).
