Problem overview
The method columnSums receives grid, an array of rows (number[][]), and returns the sum of each column from left to right. Column c is made of the value at position c in every row. The grid has 1 to 10 rows and 1 to 10 values per row.
For [[1, 2, 3], [4, 5, 6]] the columns are 1 and 4, 2 and 5, 3 and 6, so the result is [5, 7, 9]. For [[2, -1], [3, -1], [-5, 7]] it is [0, 5], and for a single row, [[4, -2, 9]], it is [4, -2, 9].
Approach: make the column the outer loop
A grid is stored as rows, so the natural loop for (const row of grid) hands over whole rows. A column is spread across all rows, one value in each. To collect it, the program needs the position of the column, so this lesson loops over indices instead of values.
The outer loop picks a column number col, from left to right, which makes the sums come out in column order. The inner loop picks a row number row and reads grid[row][col]: grid[row] is a whole row, and [col] picks this column's value from it. When the inner loop ends, the column's total is complete.
Step by step
- Create
sumsas an emptynumber[]. It collects one sum per column. - Loop over the columns:
for (let col = 0; col < grid[0].length; col++). Every row has one value per column, so the length of the first row is the number of columns. - Create
totalat 0 inside the loop, so each column starts fresh. - Loop over the rows:
for (let row = 0; row < grid.length; row++).grid.lengthis the number of rows, and a column has one number in each. - Add
grid[row][col]tototal. - Push
totalontosumsafter the inner loop, still inside the outer one. - Return
sumsafter both loops.
The solution in TypeScript
class Solution {
columnSums(grid: number[][]): number[] {
let sums: number[] = [];
for (let col = 0; col < grid[0].length; col++) {
let total = 0;
for (let row = 0; row < grid.length; row++) {
total += grid[row][col];
}
sums.push(total);
}
return sums;
}
}
Language details worth knowing:
- Row first, then column. In
grid[row][col]the first bracket picks a row and the second picks a position in it. Swapping them reads the wrong cell, and on a grid that isn't square it can reach a row that doesn't exist. - Reading past the end gives
undefined. An array doesn't throw for a bad index.grid[0][5]on a three-column grid isundefined, and addingundefinedto a number givesNaN. Reading a cell of a row that doesn't exist, such asgrid[2][0]on a two-row grid, does throw, with aTypeError, becausegrid[2]isundefined. letinforheads.let col = 0declares a counter that belongs to the loop.col++adds 1 after each pass..lengthis a property. It has no parentheses, forgrid.lengthandgrid[0].lengthalike.
Complexity
Time: O(R * C), one addition per cell. Space: O(C) for the result, one number per column.
Edge cases and common mistakes
- Swapped loop bounds. Using
grid.lengthfor the columns andgrid[0].lengthfor the rows works on a square grid and fails on a rectangular one. On[[1, 2, 3], [4, 5, 6]]the row loop would reach row 2, which doesn't exist, and the program would stop with aTypeError. - A single row.
[[4, -2, 9]]returns[4, -2, 9]: each column holds one number. - Resetting
total. It must be created inside the outer loop. Created before it, the sums would pile up from column to column. - Returning inside the outer loop. Only the first column's sum would come back.
Testing
[[1, 2, 3], [4, 5, 6]]gives[5, 7, 9].[[2, -1], [3, -1], [-5, 7]]gives[0, 5].[[4, -2, 9]]gives[4, -2, 9].
