Problem overview
The method diagonalSum receives grid, a square grid of integers with as many rows as columns, and returns the sum of the cells on its diagonal: the ones from the top-left corner to the bottom-right corner. A cell is on the diagonal when its row number and column number are equal: (0, 0), (1, 1), (2, 2) and so on. Values may be negative.
For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the diagonal cells are 1, 5 and 9, and the answer is 15. A grid with one cell, [[7]], gives 7. For [[-1, 2], [3, -4]] the diagonal holds -1 and -4, and the answer is -5. The 2 and the 3 are not on the diagonal.
Approach
A first idea is two nested loops over every cell with an if row == col test. It works, but it visits all the cells just to ignore most of them. The condition tells more: a diagonal cell is described by one number, because its row and column are the same. A single index i gives the cell grid[i][i], and running i from 0 to the last row visits exactly the diagonal cells.
So the method needs one loop and a running total. For a grid with n rows it adds n numbers instead of looking at n * n cells.
Step by step
- Create
totalwithvar, starting at 0. It grows inside the loop. - Loop over the indexes.
for i in 0..<grid.countgives one turn per row. Because the grid is square, the same range also covers every column number. - Add the diagonal cell.
total += grid[i][i]. 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 Swift
class Solution {
func diagonalSum(_ grid: [[Int]]) -> Int {
var total = 0
for i in 0..<grid.count {
total += grid[i][i]
}
return total
}
}
Swift details worth knowing:
grid[i][i]is two reads. The first gives the row, an[Int], and the second gives oneIntfrom it.- The range is half-open.
0..<grid.countstops beforegrid.count, so the last index used is the last row. Using0...grid.countwould reach one past the end and crash at run time. - The square shape is an assumption. On a grid with fewer columns than rows,
grid[i][i]would be out of range for somei, and Swift would stop the program. The lesson guarantees a square grid. +=on avar.totalmust be declared withvar; aletconstant can't be changed.
Complexity
Time is O(n) for an n by n grid, since the loop runs once per row and each pass does one addition. Space is O(1).
Edge cases and common mistakes
- One cell.
[[7]]runs the loop once withi = 0and returns 7. - Negative values. They are added like any number:
[[-1, 2], [3, -4]]gives -5. - Nested loops with a missing test. Adding every cell would give the sum of the whole grid instead of the diagonal.
- Mixing up the diagonals. This lesson asks for the top-left to bottom-right one. The other diagonal uses
grid[i][n - 1 - i]. - Looping over values.
for row in griddoes not say which row you are in. An index is needed to pick the column.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives 15.[[7]]gives 7.[[-1, 2], [3, -4]]gives -5.[[1, 2], [3, 4]]gives 5.
