Start learning free

LESSON 262 OF 291 · NESTED LOOPS OVER GRIDS

Diagonal Sum in Kotlin: One Loop over a Square Grid

Practice Read the full explanation

Given a square grid of integers grid, with as many rows as columns, return the sum of the cells on its diagonal: the cells that go from the top-left corner to the bottom-right corner.

A grid is an array of rows, and each row is an array of integers. Rows are numbered from 0, top to bottom, and columns from 0, left to right. 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.

 

Example 1:

Input: grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Output: 15
Explanation: The diagonal cells are 1, 5 and 9: 1 + 5 + 9 = 15.

Example 2:

Input: grid = [
  [7]
]
Output: 7
Explanation: A grid with one cell: that cell is the whole diagonal.

Example 3:

Input: grid = [
  [-1, 2],
  [3, -4]
]
Output: -5
Explanation: The diagonal cells are -1 and -4: -1 + (-4) = -5. The 2 and the 3 are not on the diagonal.

 

Constraints:

  • grid has n rows and n columns, with n at least 1.
  • Every value is an integer between -1000 and 1000; values can be negative.
STEP 1 OF 4
    Ctrl + Enter to check

    KOTLIN · NESTED LOOPS OVER GRIDS

    Diagonal Sum in Kotlin, explained

    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

    1. Create var total = 0. It is a var because it grows inside the loop.
    2. Write for (i in grid.indices): one turn per row, and in a square grid also one per column.
    3. In the loop, add grid[i][i] to total. The first [i] picks row i, and the second picks column i in that row.
    4. 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.indices is the range 0 to grid.size - 1. Because the grid is square, those numbers are valid column numbers too.
    • grid[i][i] first fetches the row array grid[i] and then the element at position i in it.
    • Kotlin checks array indexes at run time. If a grid had fewer columns than rows, grid[i][i] would throw an ArrayIndexOutOfBoundsException. The lesson's input is always square, so this can't happen here.
    • Negative values are added like any others, so -1 then -4 give -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.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free