Start learning free

LESSON 261 OF 293 · NESTED LOOPS OVER GRIDS

Row Sums in Rust: One Total per Row

Practice Read the full explanation

Given a grid of integers grid, return a Vec with the sum of each row, in the same order as the rows.

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.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: [6, 15]
Explanation: Row 0 adds up to 1 + 2 + 3 = 6 and row 1 to 4 + 5 + 6 = 15.

Example 2:

Input: grid = [[-1, -2],
               [-3, -4],
               [5, 5]]
Output: [-3, -7, 10]
Explanation: One sum per row, top to bottom. A row of negative numbers has a negative sum.

Example 3:

Input: grid = [[3],
               [1],
               [4]]
Output: [3, 1, 4]
Explanation: Every row has a single value, so each row's sum is that value.

 

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

    Row Sums in Rust, explained

    Problem overview

    row_sums receives a grid, a Vec<Vec<i32>> where each inner vector is a row, and returns a vector with the sum of each row, in the same order as the rows. For [[1, 2, 3], [4, 5, 6]] the result is [6, 15]. For [[-1, -2], [-3, -4], [5, 5]] it is [-3, -7, 10], and for a grid with one value per row, such as [[3], [1], [4]], each sum is that value: [3, 1, 4].

    Approach: a fresh total for every row

    This is the same pair of nested loops as summing the whole grid, with one difference in where the total lives. A sum of everything has one total for the whole grid. Here every row needs its own sum, so the total is created inside the outer loop, starting again at 0 for each row. When the inner loop finishes a row, the total holds exactly that row's sum, and it is pushed onto the result.

    Step by step

    1. Create sums. let mut sums = Vec::new(); is an empty vector that will receive one sum per row. Rust infers its type from what is pushed later.
    2. Loop over the rows. for row in &grid runs once per row, from the top.
    3. Start a row total. let mut total = 0; inside the loop, so each row begins from zero and rows never mix.
    4. Loop over the row's values. for value in row visits only the current row.
    5. Add each value. total += value;
    6. Push the total. After the inner loop, but still inside the outer one, sums.push(total) stores the finished sum. Pushing at the end of each row keeps the sums in row order.
    7. Return sums after the outer loop. Returning inside it would give back only the first row's sum.

    The solution in Rust

    impl Solution {
        fn row_sums(grid: Vec<Vec<i32>>) -> Vec<i32> {
            let mut sums = Vec::new();
            for row in &grid {
                let mut total = 0;
                for value in row {
                    total += value;
                }
                sums.push(total);
            }
            return sums;
        }
    }
    

    Rust details worth knowing:

    • Scope. A let inside a loop body creates a new variable on every turn. The total of one row is gone by the time the next row starts, which is the behaviour this problem needs.
    • total += value. value is a &i32, and Rust can add it to an i32 without a *.
    • Inference. The vector's element type is inferred as i32 from total, which itself becomes an i32 because the function returns Vec<i32>.

    Complexity

    Time: O(r * c) for r rows and c columns, as every value is added once. Space: O(r) for the returned vector, which holds one number per row.

    Edge cases and common mistakes

    • Declaring total outside the outer loop. The sums then accumulate across rows. For [[1, 2, 3], [4, 5, 6]] that code returns [6, 21] instead of [6, 15], because the second row's total starts at 6.
    • Pushing inside the inner loop. That adds a number for every value, not one per row.
    • Single-value rows. Each sum equals the value, and the result has as many entries as the grid has rows.
    • Negative values. Rows of negative numbers give negative sums, and no special case is needed.

    Testing

    • [[1, 2, 3], [4, 5, 6]] gives [6, 15].
    • [[-1, -2], [-3, -4], [5, 5]] gives [-3, -7, 10].
    • [[3], [1], [4]] gives [3, 1, 4].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free