Problem overview
The method diagonalSum receives grid, a square Array[Array[Int]] with as many rows as columns, and returns the sum of the cells on its main diagonal: the cells from the top-left corner to the bottom-right corner. Rows and columns are numbered from 0. 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.
For the 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 the single cell [[7]] the answer is 7. For [-1, 2] and [3, -4] the diagonal cells are -1 and -4, so the answer is -5, and the 2 and the 3 are ignored.
Approach: one index does both jobs
The earlier way to touch every cell is two nested loops. Here that would be wasteful: it would visit all cells to use only a few. The diagonal has a rule that removes the second loop: the row number and the column number are equal. One index i can stand for both, so grid(i)(i) is the diagonal cell of row i.
A single loop over the row numbers therefore reaches the whole diagonal, one cell per row. A grid with n rows has exactly n diagonal cells.
Step by step
- Create
var total = 0. It is avar, because it grows inside the loop. - Loop over the row numbers with
for (i <- grid.indices). There is one turn per row. - Add the diagonal cell.
total += grid(i)(i): the first(i)picks rowi, and the second picks columniin that row. - Return
totalafter the loop, once every diagonal cell has been added.
The solution in Scala
class Solution {
def diagonalSum(grid: Array[Array[Int]]): Int = {
var total = 0
for (i <- grid.indices) {
total += grid(i)(i)
}
return total
}
}
Scala details worth knowing:
- Parentheses index arrays.
grid(i)is rowi, anArray[Int], and applying(i)again reads one element. Square brackets inArray[Array[Int]]are for types only. grid.indicesis the range from 0 to the last row number, so the loop can't run past the end.- Square grids only. The code reads column
iof rowi. On a grid with more rows than columns, it would throw an exception whenigoes past the last column. The lesson guarantees a square grid. Intis enough. It is 32 bits, and diagonal sums of values within a thousand stay tiny.
Complexity
For an n by n grid, the loop runs n times and each turn does one read and one addition, so the time is O(n). That is less than the n * n cells in the grid, because most cells are never read. The extra space is O(1).
Edge cases and common mistakes
- A one-cell grid. The loop runs once and returns that cell.
- Negative values. They are added as they are: for
[[-1, 2], [3, -4]]the result is -5. - Two nested loops with a check. Looping over all cells and testing whether the row equals the column gives the same answer, but does
n * nwork for a job that needsnsteps. - Mixing up the loop variable. Writing
grid(i)(0)sums the first column, not the diagonal. - Returning inside the loop. It would stop after the first diagonal cell.
- The other diagonal. The lesson asks for the top-left to bottom-right one only. The other diagonal would need the column
n - 1 - i.
Testing
- The rows
[1, 2, 3],[4, 5, 6],[7, 8, 9]give15. [[7]]gives7.[[-1, 2], [3, -4]]gives-5.
