Problem overview
The method diagonalSum receives a square grid, grid: a list of rows with as many rows as columns. It returns the sum of the cells on the diagonal that goes from the top-left corner to the bottom-right corner. 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.
For rows [1, 2, 3], [4, 5, 6] and [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: 7. For [[-1, 2], [3, -4]] the diagonal holds -1 and -4, so the answer is -5.
Approach
The earlier grid exercises visit every cell with two nested loops. This one doesn't need that. A diagonal cell has the same number for its row and its column, so a single index i is enough to name it: the cell is grid[i][i]. One loop that counts i from 0 to the last row visits exactly the diagonal cells, one per row.
A second loop would visit every cell just to skip all but one per row. With n rows, one loop does n additions, while two nested loops would look at n * n cells.
Step by step
- Create
total = 0. No diagonal cell has been added yet. - Loop
ioverrange(len(grid)), one turn per row. - Add
grid[i][i]tototal. The first[i]picks rowi, and the second picks columniin that row. - Return
totalafter the loop, when every diagonal cell has been added.
The solution in Python
class Solution:
def diagonalSum(self, grid: List[List[int]]) -> int:
total = 0
for i in range(len(grid)):
total += grid[i][i]
return total
Python details:
- Chained indexing.
grid[i]is a list, and indexing it again with[i]gives one integer. Python evaluates left to right. len(grid)is the number of rows, which for a square grid is also the number of columns, soinever goes past the last column.- A generator expression does the same in one line:
sum(grid[i][i] for i in range(len(grid)))gives 15 for the first example. The explicit loop is the same idea with a visible counter.
The other diagonal, from the top-right corner to the bottom-left, pairs row i with column n - 1 - i. For the 3 by 3 example it adds 3, 5 and 7, which is also 15. That one is a different problem, but it uses the same single loop.
Complexity
Time: O(n) for an n by n grid, one addition per row. Space: O(1), only total and i.
Edge cases and common mistakes
- A second loop. Nesting a loop over columns and testing
row == colgives the right sum but doesn * nsteps for work that needsn. - Adding the whole row.
grid[i]is a list, sototal += grid[i]raises aTypeError. The second index selects the number. - Returning inside the loop gives only the first cell,
grid[0][0]. - One cell.
[[7]]runs the loop once and returns 7. - Negative values. They are added as usual:
[[-1, 2], [3, -4]]gives -5. - Non-square grids. The lesson guarantees a square grid. For a grid with fewer columns than rows,
grid[i][i]would eventually raise anIndexError.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives15.[[7]]gives7.[[-1, 2], [3, -4]]gives-5.
