Start learning free

LESSON 262 OF 289 · NESTED LOOPS OVER GRIDS

Diagonal Sum in TypeScript: 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

    TYPESCRIPT · NESTED LOOPS OVER GRIDS

    Diagonal Sum in TypeScript, explained

    Problem overview

    The method diagonalSum receives a square grid of integers, with as many rows as columns, and returns the sum of the cells on the diagonal from the top-left corner to the bottom-right corner. 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 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the diagonal cells are 1, 5 and 9, so the answer is 15. For [[7]] the answer is 7, and for [[-1, 2], [3, -4]] it is -5, because only -1 and -4 are on the diagonal.

    Approach: one index gives both coordinates

    The earlier grid exercises used two nested loops to visit every cell. Here only n cells matter out of n * n, and each one has the same row and column number. A single counter i can supply both, so one loop is enough: at each turn, the cell is grid[i][i]. A second loop would visit every cell only to skip almost all of them.

    The loop runs once per row, from 0 up to grid.length - 1. Because the grid is square, the same range of numbers is valid for the columns.

    Step by step

    1. Declare total with let and start it at 0. It is let because the loop changes it.
    2. Loop with i: for (let i = 0; i < grid.length; i++). grid.length is the number of rows, and it is also the number of columns.
    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. By then one cell per row has been added.

    The solution in TypeScript

    class Solution {
        diagonalSum(grid: number[][]): number {
            let total = 0;
            for (let i = 0; i < grid.length; i++) {
                total += grid[i][i];
            }
            return total;
        }
    }
    

    Language details worth knowing:

    • Chained indexing. grid[i][i] is evaluated left to right: grid[i] is a row (a number[]), and indexing that row with [i] gives a number.
    • Inferred types. let total = 0 is a number without an annotation, and i is a number as well.
    • Negative values. total += -4 subtracts 4. Nothing special is needed for them.
    • Annotations are erased. number[][] helps the compiler and the editor. The compiled JavaScript has no types.

    Complexity

    Time: O(n) for an n by n grid, since the loop runs n times and each turn does one addition. Visiting all n * n cells would cost O(n * n). Space: O(1), a single total.

    Edge cases and common mistakes

    • One cell. [[7]] runs the loop once and returns 7.
    • Only the diagonal counts. In [[-1, 2], [3, -4]] the 2 and the 3 are ignored, and the answer is -5.
    • Nested loops. Two loops with an if (row === col) inside give the same answer but do far more work.
    • Mixing up the other diagonal. The cells from the top-right corner to the bottom-left have a column number of n - 1 - i, not i. That is a different sum from the one asked for here.
    • Returning inside the loop. It would add only the first diagonal cell.
    • Non-square grids. The lesson only gives square grids. On a grid with fewer columns than rows, grid[i][i] would eventually be undefined and the total would become NaN.

    Testing

    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] gives 15.
    • [[7]] gives 7.
    • [[-1, 2], [3, -4]] gives -5.
    • [[1, 2], [3, 4]] gives 5.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free