Problem overview
The function columnSums receives grid, a vector<vector<int>>, and returns a vector<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 [[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, [[4, -2, 9]], each column holds one number, so the result is [4, -2, 9].
Approach: loop over columns on the outside
A vector of rows is organised for reading across: grid[row] is a whole row. A column isn't stored anywhere as one piece, so you collect it by taking the same position from each row. That needs indices rather than the range-based loops used for row sums.
The outer loop therefore runs over column numbers. For each column, the inner loop runs over row numbers and adds grid[row][col]. The first bracket selects a row, and the second picks the column's value in that row. When the inner loop ends, the total is that column's sum, and it is appended. Because the outer loop goes from column 0 upward, the sums come out from left to right.
The number of columns is the length of any row, since all rows have the same length. The lesson uses the first row, grid[0].size(). The number of rows is grid.size().
Step by step
- Create an empty
vector<int>namedsums. One sum per column will be added. - Loop over the column numbers. Use an
intnamedcolthat starts at 0 and runs whilecol < grid[0].size(). - Create
totalinside that loop, set to 0, so each column starts fresh. - Loop over the row numbers. Use an
intnamedrowfrom 0 whilerow < grid.size(). - Add
grid[row][col]tototal. Each turn adds the value where this row meets this column. - Append
totaltosumswithpush_back, after the inner loop but inside the outer one. - Return
sumsafter both loops.
The solution in C++
class Solution {
public:
vector<int> columnSums(vector<vector<int>> &grid) {
vector<int> sums;
for (int col = 0; col < grid[0].size(); col++) {
int total = 0;
for (int row = 0; row < grid.size(); row++) {
total += grid[row][col];
}
sums.push_back(total);
}
return sums;
}
};
C++ details:
size()is unsigned. It returns an unsigned integer type, and the loop variables areint. Comparing the two works for sizes this small, and the compiler may warn about mixing signed and unsigned values. If a vector were empty,v.size() - 1would wrap around to a huge number (18446744073709551615 with a 64-bitsize_t) instead of -1, so be careful with subtraction on sizes.- No bounds checking with
[].grid[row][col]doesn't verify the indices. An index outside the vector is undefined behaviour, not an error message. Both loop bounds are chosen so the indices stay valid. grid[0]needs a first row. Readinggrid[0].size()is valid only when the grid has at least one row. The lesson guarantees that, but a function that must accept an empty grid would checkgrid.empty()first.
Complexity
For R rows and C columns, each of the C outer turns runs R inner turns, so the time is O(R * C). The result takes O(C) space and the loops add only constants.
Edge cases and common mistakes
- Swapped indices.
grid[col][row]reads the wrong cells and, for a grid that isn't square, goes out of range. The row index always goes first. - One row.
[[4, -2, 9]]returns[4, -2, 9]. - One column.
[[3], [1], [4]]returns[8]. - Total outside the outer loop. The sums would accumulate across columns, so each result would include all the columns before it.
- Using
grid.size()for the columns. That is the number of rows. For a 2 by 3 grid, the loop would stop after two columns.
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].[[3], [1], [4]]gives[8].
