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
- Create
int total = 0. No diagonal cell has been added yet. - 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, soiis always a valid column too. - Add
grid[i][i]tototalwith+=. The first[i]picks rowi, and the second picks columniin that row. - Return
totalafter 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 anint[], and the second[i]reads from it. A rectangularint[,]would be writtengrid[i, i]instead. This lesson's type isint[][]. - The square shape is what makes this safe. If a row were shorter than
i + 1, readinggrid[i][i]would throwIndexOutOfRangeException. On a square grid every row has at least as many values as there are rows. +=.total += grid[i][i]is shorthand fortotal = total + grid[i][i].- Overflow. An
intwraps 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.Lengthmakes the last turn readgrid[n], which throwsIndexOutOfRangeException.
Testing
grid | Result |
|---|---|
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] | 15 |
[[7]] | 7 |
[[-1, 2], [3, -4]] | -5 |
