Problem overview
diagonal_sum receives a square grid, a Vec<Vec<i32>> with as many rows as columns, and returns the sum of the cells on the diagonal from the top-left corner to the bottom-right one. A cell is on the diagonal when its row number equals its column number: (0, 0), (1, 1), (2, 2) and so on. For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the diagonal cells are 1, 5 and 9, so the answer is 15. For [[7]] it is 7, and for [[-1, 2], [3, -4]] it is -5.
Approach: one index does the job of two
With the nested loops used for the other grid problems, most cells would be visited just to be skipped. The diagonal is simpler: the row and the column are always the same number, so a single index i names the cell. One loop over i adds grid[i][i] for each row, and that is all.
Step by step
- Create the total.
let mut total = 0;is mutable because it grows in the loop. Rust makes it ani32, the type of the grid's numbers. - Loop over the rows.
for i in 0..grid.len()gives one turn per row. In a square grid that is also one turn per column. - Add the diagonal cell.
total += grid[i][i];. The first[i]selects rowi, and the second selects columniin that row. - Return after the loop, when every diagonal cell has been added.
The solution in Rust
impl Solution {
fn diagonal_sum(grid: Vec<Vec<i32>>) -> i32 {
let mut total = 0;
for i in 0..grid.len() {
total += grid[i][i];
}
return total;
}
}
Rust details worth knowing:
iis ausize.grid.len()is ausize, so the range0..grid.len()producesusizevalues, which is what indexing needs.- Copying out of the grid.
grid[i][i]is ani32, which isCopy, so adding it tototalleaves the grid unchanged. - Indexing is checked. If a row were shorter than the grid has rows,
grid[i][i]would panic. For[[1], [2]]the program stops withindex out of bounds: the len is 1 but the index is 1. The lesson guarantees a square grid, so this does not happen.
Following the loop
On the 3 by 3 example, the loop runs three times. With i = 0 it adds grid[0][0], which is 1. With i = 1 it adds grid[1][1], which is 5, and with i = 2 it adds grid[2][2], which is 9. The total goes 1, 6, 15. The cells in between, such as 2 and 4, are never read at all.
Complexity
Time: O(n) for an n by n grid, since the loop runs n times and each turn reads one cell. That is less than the O(n²) of a full pass over the grid. Space: O(1), because only total and i are stored.
Edge cases and common mistakes
- A one-cell grid. The loop runs once and the cell is the whole diagonal.
- Negative values. They are added like any other number, so
[[-1, 2], [3, -4]]gives -5. - The other diagonal. The cells from the top-right to the bottom-left are not
grid[i][i]. In a grid withnrows they aregrid[i][n - 1 - i]. In the first example that diagonal is 3, 5 and 7, but this lesson only asks for the main one. - Adding the off-diagonal cells. The 2 and the 3 in the last example must not be added.
- Returning inside the loop. Only the first diagonal cell would be counted.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives15.[[7]]gives7.[[-1, 2], [3, -4]]gives-5.
