Problem overview
Given a square grid grid of type int[][], with as many rows as columns, diagonalSum returns the sum of the cells on the diagonal that runs from the top-left corner to the bottom-right one. A cell is on the diagonal when its row number and column number are the same: row 0 and column 0, row 1 and column 1, and so on. Rows and columns are counted from 0.
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]] the single cell is the whole diagonal, and the answer is 7. For [[-1, 2], [3, -4]] the diagonal cells are -1 and -4, so the answer is -5; the 2 and the 3 are not on the diagonal.
Approach
Summing a grid usually takes two loops, one over rows and one over columns. Here that would be wasteful: a nested pair of loops would visit every cell only to skip most of them. The diagonal has a simple rule, though: the row number equals the column number. So one index i is enough to name each diagonal cell, as grid[i][i].
The loop runs i from 0 up to the number of rows, and each turn adds one diagonal cell. A grid with n rows has exactly n diagonal cells, so the loop runs n times.
Step by step
- Create an
intnamedtotalstarting at 0. No diagonal cell has been added yet. - Write a
forloop with anintifrom 0 whilei < grid.length. That is one turn per row, and since the grid is square, one turn per column too. - Inside the loop, add
grid[i][i]tototalwith+=. The first[i]picks rowi, and the second picks columniin that row. - After the loop, return
total. By then every diagonal cell has been added, one per row.
Tracing the first example
For the 3 by 3 grid with 1 to 9, the loop reads grid[0][0], which is 1, then grid[1][1], which is 5, then grid[2][2], which is 9. The total goes 1, 6, 15, and the method returns 15.
The solution in Java
class Solution {
public int diagonalSum(int[][] grid) {
int total = 0;
for (int i = 0; i < grid.length; i++) {
total += grid[i][i];
}
return total;
}
}
Java details in this code:
- An index loop, not for-each. The for-each form gives values without their positions. The diagonal depends on positions, so the loop needs the index
i. grid[i][i]is two lookups.grid[i]is the row, anint[], and the second[i]indexes into it.grid.lengthcounts rows. It is a field with no parentheses. For a square grid, it is also the column count, which is why one bound is enough.- Bad indexes throw. If the grid were not square, an index could run past a row's end. The lesson guarantees a square grid, so it doesn't happen here.
Complexity
The loop runs once per row, doing one addition each time, so the time is O(n) for an n by n grid. It doesn't depend on the n * n cells, because the other cells are never read. The extra space is O(1): one variable for the total and one for the index.
Edge cases and common mistakes
- A one-cell grid.
[[7]]hasgrid.lengthequal to 1, so the loop runs once and the method returns 7. - Negative values. They lower the total. For
[[-1, 2], [3, -4]], the sum is -1 plus -4, which is -5. - Nested loops with a check. Writing two loops and adding a cell only when
row == colgives the same answer, but it readsn * ncells wherenare needed. - Counting the middle twice. This task asks only for the main diagonal, from the top left to the bottom right. The other diagonal has the cells
grid[i][n - 1 - i], and a task that adds both would need to count the center cell of an odd-sized grid once. - A wider grid. The lesson promises a square grid. If you passed
[[1, 2, 3], [4, 5, 6]], which has two rows and three columns, the loop would add 1 and 5 and return 6, which is not a diagonal sum in the lesson's sense.
Testing
diagonalSum(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})returns 15.diagonalSum(new int[][]{{7}})returns 7.diagonalSum(new int[][]{{-1, 2}, {3, -4}})returns -5.
