Start learning free

LESSON 260 OF 293 · NESTED LOOPS OVER GRIDS

Grid Sum in Rust: Nested Loops over a Vec of Vecs

Practice Read the full explanation

Given a grid of integers grid, return the sum of all the numbers in it.

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: 21
Explanation: The first row adds up to 1 + 2 + 3 = 6 and the second to 4 + 5 + 6 = 15. Together: 6 + 15 = 21.

Example 2:

Input: grid = [[-3, 4],
               [5, -6]]
Output: 0
Explanation: -3 + 4 + 5 + (-6) = 0. Negative numbers make the sum smaller.

Example 3:

Input: grid = [[7]]
Output: 7
Explanation: A grid with one row and one column holds a single 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 5
    Ctrl + Enter to check

    RUST · NESTED LOOPS OVER GRIDS

    Grid Sum in Rust, explained

    Problem overview

    A grid is a table of numbers made of rows, and in Rust it is a Vec<Vec<i32>>: a vector whose elements are themselves vectors, one per row. grid_sum returns the sum of every number in it. For the grid [[1, 2, 3], [4, 5, 6]] the first row adds up to 6 and the second to 15, so the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, and for [[7]] it is 7.

    Approach: one loop inside another

    One loop can only walk through one vector at a time, and a grid is a vector of vectors. So the outer loop takes the rows one by one, and for each row an inner loop takes its values one by one. Together the two loops visit every cell exactly once, and each value is added to a running total.

    Step by step

    1. Create the total. let mut total = 0; starts the sum at 0, because nothing has been added yet. It is mut because it changes in the loops.
    2. Loop over the rows. for row in &grid borrows the grid and gives each row as a reference to a Vec<i32>.
    3. Loop over one row. for value in row goes through the values of that row. This inner loop finishes the whole row before the outer loop moves to the next one.
    4. Add the value. total += value; adds it to the sum. Negative values reduce the total, as they should.
    5. Return after both loops. Returning inside them would add only part of the grid.

    The solution in Rust

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

    Rust details worth knowing:

    • Borrowing the grid. Looping over &grid lends each row to the loop instead of moving it out of the vector. Since row is already a reference, for value in row needs no extra &.
    • value is a &i32. Rust lets total += value add a reference to an i32 directly, so no * is needed here. When you compare a reference with a number, as in *value == target, you do need it.
    • The type of total. It starts as a bare 0, and the function's return type makes it an i32.

    Complexity

    Time: O(r * c) for a grid of r rows and c columns, because every cell is added once. Space: O(1), as the code keeps only total and the loop variables.

    Edge cases and common mistakes

    • A single cell. For [[7]] both loops run once and the result is 7.
    • Overflow. With at most 10 rows and 10 columns of values between -1000 and 1000, the sum stays between -100000 and 100000, far inside the i32 range. A grid of one hundred 1000s gives 100000.
    • Returning too early. A return inside either loop would stop after the first row or the first value.
    • Resetting the total. The total is created once, before both loops. Creating it inside the outer loop would throw away the earlier rows' sums.

    Testing

    • [[1, 2, 3], [4, 5, 6]] gives 21.
    • [[-3, 4], [5, -6]] gives 0.
    • [[7]] gives 7.
    • Ten rows of ten 1000s gives 100000, and ten rows of ten -1000s gives -100000.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free