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
- Create the total.
let mut total = 0;starts the sum at 0, because nothing has been added yet. It ismutbecause it changes in the loops. - Loop over the rows.
for row in &gridborrows the grid and gives eachrowas a reference to aVec<i32>. - Loop over one row.
for value in rowgoes through the values of that row. This inner loop finishes the whole row before the outer loop moves to the next one. - Add the value.
total += value;adds it to the sum. Negative values reduce the total, as they should. - 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
&gridlends each row to the loop instead of moving it out of the vector. Sincerowis already a reference,for value in rowneeds no extra&. valueis a&i32. Rust letstotal += valueadd a reference to ani32directly, 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 bare0, and the function's return type makes it ani32.
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
i32range. A grid of one hundred 1000s gives 100000. - Returning too early. A
returninside 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]]gives21.[[-3, 4], [5, -6]]gives0.[[7]]gives7.- Ten rows of ten 1000s gives
100000, and ten rows of ten -1000s gives-100000.
