Start learning free

LESSON 262 OF 293 · NESTED LOOPS OVER GRIDS

Column Sums in Rust: Looping by Index

Practice Read the full explanation

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

    RUST · NESTED LOOPS OVER GRIDS

    Column Sums in Rust, explained

    Problem overview

    column_sums receives a grid, a Vec<Vec<i32>> of rows, and returns 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]] column 0 holds 1 and 4, column 1 holds 2 and 5, and column 2 holds 3 and 6, so the result is [5, 7, 9]. For [[2, -1], [3, -1], [-5, 7]] the result is [0, 5], and for the single row [[4, -2, 9]] it is [4, -2, 9].

    Approach: columns outside, rows inside

    A grid is stored as rows, so a column is not a vector you can loop over directly. It is spread across the rows: one value from each. The way to reach it is by index. The outer loop picks a column number, and the inner loop walks the row numbers and adds grid[row][col] each time. Compared with the row sums, the two loops swap roles: the outer one now decides which total is being built.

    That also means the loops are over numbers, not over the values themselves, so the loop variables are indices.

    Step by step

    1. Create sums. An empty mutable Vec that will hold one sum per column.
    2. Loop over column numbers. for col in 0..grid[0].len(). Every row has one value per column, so the length of the first row is the number of columns. The sums come out in column order because col counts upward from 0.
    3. Start a column total. let mut total = 0; inside the loop, so each column begins from zero.
    4. Loop over row numbers. for row in 0..grid.len() visits each row once, because a column has one value in every row.
    5. Add one cell. total += grid[row][col]; reads row row first, then the value at position col in it.
    6. Push the total. After the inner loop, sums.push(total) stores the finished column sum.
    7. Return sums after both loops.

    The solution in Rust

    impl Solution {
        fn column_sums(grid: Vec<Vec<i32>>) -> Vec<i32> {
            let mut sums = Vec::new();
            for col in 0..grid[0].len() {
                let mut total = 0;
                for row in 0..grid.len() {
                    total += grid[row][col];
                }
                sums.push(total);
            }
            return sums;
        }
    }
    

    Rust details worth knowing:

    • Indices are usize. grid.len() and grid[0].len() are usize, so col and row are too, which is the type Rust requires for indexing a vector. No cast is needed.
    • Out-of-bounds access panics. Rust checks every index. On an empty grid, grid[0] stops the program with index out of bounds: the len is 0 but the index is 0. The lesson guarantees at least one row, so the code does not guard against it.
    • Two [ ] in a row. grid[row] is a whole Vec<i32>, and the second [col] picks one number from it.

    Complexity

    Time: O(r * c) for r rows and c columns, because every cell is read once. Space: O(c) for the returned vector, one number per column.

    Edge cases and common mistakes

    • Swapping the two indices. grid[col][row] reads the wrong cell, and on a grid that is not square it goes out of bounds. The row always comes first.
    • Using the wrong length. The number of columns is grid[0].len(). Using grid.len() in the outer loop would count rows instead.
    • One row. Every column holds a single number, so the result is the row itself.
    • Not resetting the total. The total belongs inside the outer loop. Created outside it, a column's sum would include the earlier columns.
    • Returning early. A return inside the outer loop would give back only the first column.

    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].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free