Problem overview
Given a square grid of integers, with as many rows as columns, return the sum of the cells on its diagonal: the cells 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. In Kotlin the grid is an Array<IntArray>.
For the 3 by 3 grid with rows [1, 2, 3], [4, 5, 6] and [7, 8, 9], the diagonal cells are 1, 5 and 9, and the sum is 15. A one-cell grid [7] gives 7. For [-1, 2] and [3, -4] the diagonal holds -1 and -4, so the answer is -5, and the 2 and 3 are not counted.
Approach
The tempting solution is two nested loops that visit every cell and add it when the row equals the column. It works, but it visits all n by n cells to use only n of them. The diagonal cells are described by one number: cell i is at row i and column i. So one loop over i is enough, and it reads exactly the cells you need.
Step by step
- Create
var total = 0. It is avarbecause it grows inside the loop. - Write
for (i in grid.indices): one turn per row, and in a square grid also one per column. - In the loop, add
grid[i][i]tototal. The first[i]picks rowi, and the second picks columniin that row. - After the loop,
return total. By then one cell has been added per row.
The solution in Kotlin
class Solution {
fun diagonalSum(grid: Array<IntArray>): Int {
var total = 0
for (i in grid.indices) {
total += grid[i][i]
}
return total
}
}
Some Kotlin details:
grid.indicesis the range0togrid.size - 1. Because the grid is square, those numbers are valid column numbers too.grid[i][i]first fetches the row arraygrid[i]and then the element at positioniin it.- Kotlin checks array indexes at run time. If a grid had fewer columns than rows,
grid[i][i]would throw anArrayIndexOutOfBoundsException. The lesson's input is always square, so this can't happen here. - Negative values are added like any others, so
-1then-4give-5.
Complexity
The loop runs n times for an n by n grid, so the time is O(n). Checking every cell with nested loops would take O(n²). The extra space is O(1).
Edge cases and common mistakes
- A nested loop. Two loops with an
if (row == col)give the same answer more slowly. One index does the job. - Adding the other diagonal. The top-right to bottom-left diagonal is a different set of cells. This lesson only asks for the main one.
- One cell. The loop runs once, and the answer is that cell.
- Returning inside the loop. That would stop after the first cell.
Testing
- The grid of 1 to 9 in three rows gives 15.
- The one-cell grid
[7]gives 7. - Rows
[-1, 2]and[3, -4]give -5.
