Problem overview
Given a grid grid of type int[][], columnSums returns a list with the sum of each column, from left to right. Every row has the same number of values, and rows and columns are counted from 0. Column c is made of the value at position c in every row.
For [[1, 2, 3], [4, 5, 6]] the result is [5, 7, 9]: column 0 holds 1 and 4, column 1 holds 2 and 5, and column 2 holds 3 and 6. For [[2, -1], [3, -1], [-5, 7]] it is [0, 5]. For a single row such as [[4, -2, 9]], every column holds one number, so the result is [4, -2, 9].
Approach
Summing rows is easy in Java because an int[][] is an array of rows: a for-each loop hands you one row at a time. Columns have no such shortcut. There is no object that is "column 1"; a column is spread across the rows, one value from each. So the loops need numbers, not just values.
The plan is to loop over column numbers on the outside and row numbers on the inside. For a fixed column col, the inner loop visits grid[row][col] for every row and adds them up. Looping over columns first means one column is finished before the next starts, so the sums are saved in left-to-right order.
Step by step
- Create
sums, an emptyList<Integer>backed by a newArrayList. It will collect one sum per column. - Write a
forloop with anintcolfrom 0 whilecol < grid[0].length. Every row has one value per column, so the length of the first row is the number of columns. - Inside it, create an
intnamedtotalstarting at 0. It is created again for each column, so the columns' numbers never mix. - Below that, write an inner
forloop with anintrowfrom 0 whilerow < grid.length, the number of rows. A column has one number in every row, so this loop visits each row once. - Inside the inner loop, add
grid[row][col]tototal. The expressiongrid[row]is a whole row, and[col]then picks this column's number out of it. - After the inner loop, still inside the outer one, call
sums.add(total). Every row's number in this column has been added, sototalis the column's sum. - After both loops, return
sums.
Tracing the first example
For [[1, 2, 3], [4, 5, 6]], grid.length is 2 and grid[0].length is 3. The outer loop runs for col 0, 1 and 2. For col = 0, the inner loop adds grid[0][0] and grid[1][0], which are 1 and 4. The other two columns work the same way, and the method returns [5, 7, 9].
The solution in Java
class Solution {
public List<Integer> columnSums(int[][] grid) {
List<Integer> sums = new ArrayList<>();
for (int col = 0; col < grid[0].length; col++) {
int total = 0;
for (int row = 0; row < grid.length; row++) {
total += grid[row][col];
}
sums.add(total);
}
return sums;
}
}
Java details in this code:
- Row first, then column.
grid[row][col]is always written row index first.grid.lengthcounts rows, andgrid[0].lengthcounts the values in the first row, which is the number of columns. lengthhas no parentheses on arrays. It is a field, so it isgrid.length, notgrid.length(). AListusessize()instead.- Out-of-range indexes throw. Java doesn't wrap or ignore a bad index: it throws
ArrayIndexOutOfBoundsException. With a grid whose rows differ in length, such as{{1, 2}, {3}}, this method fails with "Index 1 out of bounds for length 1". The lesson guarantees equal rows, so it doesn't come up. - The imports.
ListandArrayListare injava.util: a standalone program needsimport java.util.*;.
Complexity
With R rows and C columns, the inner loop body runs R times for each of the C columns, so every cell is visited once: O(R * C) time. The result list holds C numbers, so the extra space is O(C).
Edge cases and common mistakes
- Swapping the indexes. Writing
grid[col][row]reads the grid transposed. For the 2 by 3 grid[[1, 2, 3], [4, 5, 6]]it throws "Index 2 out of bounds for length 2", becausecolreaches 2 and there are only two rows. In a square grid it wouldn't crash and would silently return the row sums instead. - Using
grid.lengthas the column count. That is the number of rows. The two are equal only in a square grid. - Declaring
totaloutside the outer loop. Each column's total would start from the previous one. - A single row.
[[4, -2, 9]]gives[4, -2, 9]: the inner loop runs once per column, and each sum is that one number. - Negative values. They simply lower the sums. Column 0 of the second example is 2 + 3 + (-5), which is 0.
Testing
columnSums(new int[][]{{1, 2, 3}, {4, 5, 6}})returns[5, 7, 9].columnSums(new int[][]{{2, -1}, {3, -1}, {-5, 7}})returns[0, 5].columnSums(new int[][]{{4, -2, 9}})returns[4, -2, 9].
