Start learning free

LESSON 254 OF 281 · NESTED LOOPS OVER GRIDS

Column Sums in C++: Indexing a Vector of Vectors

Practice Read the full explanation

Given a grid of integers grid, return a vector 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

    C++ · NESTED LOOPS OVER GRIDS

    Column Sums in C++, explained

    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

    1. Create an empty vector<int> named sums. One sum per column will be added.
    2. Loop over the column numbers. Use an int named col that starts at 0 and runs while col < grid[0].size().
    3. Create total inside that loop, set to 0, so each column starts fresh.
    4. Loop over the row numbers. Use an int named row from 0 while row < grid.size().
    5. Add grid[row][col] to total. Each turn adds the value where this row meets this column.
    6. Append total to sums with push_back, after the inner loop but inside the outer one.
    7. Return sums after 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 are int. 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() - 1 would wrap around to a huge number (18446744073709551615 with a 64-bit size_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. Reading grid[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 check grid.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].
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free