Start learning free

LESSON 261 OF 289 · NESTED LOOPS OVER GRIDS

Diagonal Sum in C#: grid[i][i] in a Single Loop

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

    C# · NESTED LOOPS OVER GRIDS

    Diagonal Sum in C#, explained

    Problem overview

    DiagonalSum receives a square grid, an int[][] with as many rows as columns, and returns the sum of the cells on its diagonal: the ones that run from the top-left corner to the bottom-right corner. A cell is on the diagonal when its row number and column number are the same: (0, 0), (1, 1), (2, 2) and so on. Rows and columns are numbered from 0.

    For the grid [1, 2, 3], [4, 5, 6], [7, 8, 9], the diagonal cells are 1, 5 and 9, and 1 + 5 + 9 = 15. For the one-cell grid [7] the answer is 7. For [-1, 2], [3, -4] it is -1 + (-4) = -5: the 2 and the 3 are not on the diagonal.

    Approach: one index gives both coordinates

    The earlier grid lessons visit every cell with two loops. Here almost every cell is irrelevant: only the cells where the row number equals the column number count. A single index i is enough to name them, because the cell is grid[i][i]. The loop runs i from 0 to the last row, and each turn picks one diagonal cell.

    A nested loop would also work, with an if (row == col) inside, but it would visit every cell just to skip most of them. For a grid with n rows that is n × n visits instead of n.

    Step by step

    1. Create int total = 0. No diagonal cell has been added yet.
    2. Loop with for (int i = 0; i < grid.Length; i++). That is one turn per row. Because the grid is square, the number of rows is also the number of columns, so i is always a valid column too.
    3. Add grid[i][i] to total with +=. The first [i] picks row i, and the second picks column i in that row.
    4. Return total after the loop. By then every diagonal cell has been added, one per row.

    The solution in C#

    class Solution {
        public int DiagonalSum(int[][] grid) {
            int total = 0;
            for (int i = 0; i < grid.Length; i++) {
                total += grid[i][i];
            }
            return total;
        }
    }
    

    C# details:

    • Jagged indexing. grid[i][i] works in two steps: grid[i] is an int[], and the second [i] reads from it. A rectangular int[,] would be written grid[i, i] instead. This lesson's type is int[][].
    • The square shape is what makes this safe. If a row were shorter than i + 1, reading grid[i][i] would throw IndexOutOfRangeException. On a square grid every row has at least as many values as there are rows.
    • +=. total += grid[i][i] is shorthand for total = total + grid[i][i].
    • Overflow. An int wraps silently when it gets too big in C#. The numbers here are small enough that the sum never gets near the limit.

    Complexity

    The loop makes one pass over the rows, so the time is O(n) for an n by n grid, and the method uses a constant amount of extra memory. The grid has n × n cells, so the method reads only a small fraction of them.

    Edge cases and common mistakes

    • A one-by-one grid. The loop runs once and returns the only cell.
    • Negative values. They are added like any other number, so a diagonal can sum to a negative result, as in the third example.
    • The other diagonal. This lesson sums top-left to bottom-right. The cells of the other diagonal have a column of grid.Length - 1 - i, and they are not summed here. For the first example that is 3, 5 and 7, which happens to add up to 15 as well, so a grid with an asymmetric diagonal is a better test.
    • Using a second loop. It still gives the right answer when guarded by row == col, but it does n times more work than needed.
    • Going past the last row. A condition such as i <= grid.Length makes the last turn read grid[n], which throws IndexOutOfRangeException.

    Testing

    gridResult
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]15
    [[7]]7
    [[-1, 2], [3, -4]]-5
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free