Start learning free

LESSON 262 OF 291 · NESTED LOOPS OVER GRIDS

Diagonal Sum in Scala: One Loop and grid(i)(i)

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

    SCALA · NESTED LOOPS OVER GRIDS

    Diagonal Sum in Scala, explained

    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

    1. Create var total = 0. It is a var, because it grows inside the loop.
    2. Loop over the row numbers with for (i <- grid.indices). There is one turn per row.
    3. Add the diagonal cell. total += grid(i)(i): the first (i) picks row i, and the second picks column i in that row.
    4. Return total after 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 row i, an Array[Int], and applying (i) again reads one element. Square brackets in Array[Array[Int]] are for types only.
    • grid.indices is 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 i of row i. On a grid with more rows than columns, it would throw an exception when i goes past the last column. The lesson guarantees a square grid.
    • Int is 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 * n work for a job that needs n steps.
    • 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] give 15.
    • [[7]] gives 7.
    • [[-1, 2], [3, -4]] gives -5.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free