Start learning free

LESSON 265 OF 293 · NESTED LOOPS OVER GRIDS

Diagonal Sum in Rust: One Loop, grid[i][i]

Practice Read the full explanation

Given a square grid of integers grid, with as many rows as columns, return the sum of the cells on its diagonal: the cells that go from the top-left corner to the bottom-right corner.

A grid is an array of rows, and each row is an array of integers. Rows are numbered from 0, top to bottom, and columns from 0, left to right. A cell is on the diagonal when its row number and its column number are the same: row 0 and column 0, row 1 and column 1, and so on.

 

Example 1:

Input: grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Output: 15
Explanation: The diagonal cells are 1, 5 and 9: 1 + 5 + 9 = 15.

Example 2:

Input: grid = [
  [7]
]
Output: 7
Explanation: A grid with one cell: that cell is the whole diagonal.

Example 3:

Input: grid = [
  [-1, 2],
  [3, -4]
]
Output: -5
Explanation: The diagonal cells are -1 and -4: -1 + (-4) = -5. The 2 and the 3 are not on the diagonal.

 

Constraints:

  • grid has n rows and n columns, with n at least 1.
  • Every value is an integer between -1000 and 1000; values can be negative.
STEP 1 OF 4
    Ctrl + Enter to check

    RUST · NESTED LOOPS OVER GRIDS

    Diagonal Sum in Rust, explained

    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

    1. Create the total. let mut total = 0; is mutable because it grows in the loop. Rust makes it an i32, the type of the grid's numbers.
    2. 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.
    3. Add the diagonal cell. total += grid[i][i];. The first [i] selects row i, and the second selects column i in that row.
    4. 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:

    • i is a usize. grid.len() is a usize, so the range 0..grid.len() produces usize values, which is what indexing needs.
    • Copying out of the grid. grid[i][i] is an i32, which is Copy, so adding it to total leaves 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 with index 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 with n rows they are grid[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]] gives 15.
    • [[7]] gives 7.
    • [[-1, 2], [3, -4]] gives -5.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free