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
- 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. - Loop over the rows.
for row in &gridruns once per row, from the top. - Start a row total.
let mut total = 0;inside the loop, so each row begins from zero and rows never mix. - Loop over the row's values.
for value in rowvisits only the current row. - Add each value.
total += value; - 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. - Return
sumsafter 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
letinside a loop body creates a new variable on every turn. Thetotalof one row is gone by the time the next row starts, which is the behaviour this problem needs. total += value.valueis a&i32, and Rust can add it to ani32without a*.- Inference. The vector's element type is inferred as
i32fromtotal, which itself becomes ani32because the function returnsVec<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
totaloutside 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].
