Start learning free

LESSON 257 OF 289 · NESTED LOOPS OVER GRIDS

Grid Sum in TypeScript: Nested for...of Loops

Practice Read the full explanation

Given a grid of integers grid, return the sum of all the numbers in it.

A grid is a table of numbers made of rows. Every row has the same number of values, one in each column. Rows are counted from the top and columns from the left, both starting at 0.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: 21
Explanation: The first row adds up to 1 + 2 + 3 = 6 and the second to 4 + 5 + 6 = 15. Together: 6 + 15 = 21.

Example 2:

Input: grid = [[-3, 4],
               [5, -6]]
Output: 0
Explanation: -3 + 4 + 5 + (-6) = 0. Negative numbers make the sum smaller.

Example 3:

Input: grid = [[7]]
Output: 7
Explanation: A grid with one row and one column holds a single number.

 

Constraints:

  • grid has at least 1 row and at most 10 rows.
  • Every row has the same number of values, at least 1 and at most 10.
  • Every value is an integer between -1000 and 1000.
STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · NESTED LOOPS OVER GRIDS

    Grid Sum in TypeScript, explained

    Problem overview

    The method gridSum receives grid, a table of integers stored as an array of rows (number[][]), and returns the sum of all its numbers. The grid has between 1 and 10 rows, every row has the same number of values, and the values can be negative.

    For [[1, 2, 3], [4, 5, 6]] the first row adds up to 6 and the second to 15, so the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, and a grid with a single number, [[7]], gives 7.

    Approach: a loop inside a loop

    A grid is an array that contains arrays. Going through a plain array takes one loop; going through every cell of a grid takes two. The outer loop picks the rows one at a time. For each row, the inner loop visits all of its values before the outer loop moves on. Together the loops visit every cell exactly once, so adding each value to a running total gives the sum of the whole grid.

    The running total is created before the loops and returned after them. It must live outside both loops: if it were declared inside the outer loop, it would start again from 0 for every row.

    Step by step

    1. Create total with let and start it at 0. No number has been added yet. It is let because its value changes.
    2. Loop over the rows with for (const row of grid). Each item of grid is itself an array of numbers, so row is a number[].
    3. Loop over one row with for (const value of row), inside the first loop. For every row, this loop runs once per value.
    4. Add the value: total += value. Negative values make the total smaller, which needs no special handling.
    5. Return total after both loops. Returning inside a loop would stop after the first row or the first value.

    The solution in TypeScript

    class Solution {
        gridSum(grid: number[][]): number {
            let total = 0;
            for (const row of grid) {
                for (const value of row) {
                    total += value;
                }
            }
            return total;
        }
    }
    

    Language details worth knowing:

    • for...of gives values. It hands you each item of an array directly, with no index to manage. The loop variable is declared with const because each turn gets a fresh one that is never reassigned.
    • No annotation on total. TypeScript infers number from the starting value 0, so let total = 0 is the same as let total: number = 0.
    • number[][]. It means an array whose items are arrays of numbers. Like all annotations it is erased when the code is compiled to JavaScript.
    • +=. total += value is shorthand for total = total + value.

    Complexity

    Time: O(R * C) for a grid with R rows and C columns, because each of the R * C cells is visited once. Space: O(1): only total is stored besides the input.

    Edge cases and common mistakes

    • One cell. [[7]] runs both loops once and returns 7.
    • Cancelling values. [[-3, 4], [5, -6]] returns 0.
    • Declaring total in the wrong place. Inside the outer loop it resets for each row, and the function can't see it after the loops.
    • Using for...in. On an array it gives the indices as strings, so adding them would join text instead of adding numbers.
    • Returning too early. A return inside a loop adds only part of the grid.

    Testing

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