Problem overview
The function diagonalSum receives grid, a square [][]int with as many rows as columns, and returns the sum of the cells on the diagonal that runs from the top-left corner to the bottom-right corner. A cell is on that diagonal when its row number and its column number are equal: (0, 0), (1, 1), (2, 2) and so on.
For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the diagonal cells are 1, 5 and 9, and the answer is 15. For [[7]] the answer is 7, and for [[-1, 2], [3, -4]] it is -5: the cells -1 and -4 are on the diagonal, while the 2 and the 3 are not.
Approach: one index does both jobs
It is tempting to reach for two nested loops, as in the other grid lessons, and skip every cell whose row and column differ. That works but wastes effort: on an n by n grid it looks at n * n cells to use n of them.
The diagonal cell of row i is always in column i, so a single index gives both coordinates. One loop over the row numbers, adding grid[i][i] each time, visits exactly the diagonal and nothing else.
Step by step
- Create
totalwith:=, starting at 0. - Loop over the row numbers:
for i := range grid. With one variable,rangegives the indexes 0, 1, 2 and so on: one turn per row. - Add the diagonal cell:
total += grid[i][i]. The first[i]picks rowi, and the second picks columniinside that row. - Return
totalafter the loop. By then every diagonal cell has been added, one per row.
The solution in Go
func diagonalSum(grid [][]int) int {
total := 0
for i := range grid {
total += grid[i][i]
}
return total
}
Go details:
for i := range gridgives only the index of each element, because only one loop variable is named. That is what the code needs, since it looks the cells up itself.- Chained indexing.
grid[i][i]first takesgrid[i], a[]int, then elementiof it. - Index checks happen at run time. If a row were shorter than the number of rows,
grid[i][i]would stop the program withindex out of range. For a grid with two rows of one value each,[[1], [4]], the second turn fails withindex out of range [1] with length 1. The lesson's grids are square, so this can't happen there. - Non-square grids don't always fail. A 2 by 3 grid such as
[[1, 2, 3], [4, 5, 6]]doesn't panic and returns 6, the sum of 1 and 5. It is simply outside what the lesson asks.
Edge cases and common mistakes
- A one-cell grid.
[[7]]runs the loop once and addsgrid[0][0], so the answer is 7. - Negative values. They are added like any others: for
[[-1, 2], [3, -4]]the sum is -1 + (-4) = -5. - Adding the wrong cells. Off-diagonal cells such as the 2 and the 3 above must not be counted.
grid[i][i]can't reach them. - Nesting a second loop. A loop over columns inside the first would visit every cell and need an
if i == jtest. The answer would be the same, but the work is quadratic instead of linear. - Returning inside the loop. That would add only the first diagonal cell.
Complexity
Time: O(n) for an n by n grid, because the loop runs n times and each turn does one addition. Space: O(1), since only total and the loop index are kept.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives15.[[7]]gives7.[[-1, 2], [3, -4]]gives-5.
