Start learning free

LESSON 259 OF 289 · NESTED LOOPS OVER GRIDS

Column Sums in TypeScript: Looping by Index

Practice Read the full explanation

Given a grid of integers grid, return an array with the sum of each column, from left to right.

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.

Column c is made of the value at position c in every row.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: [5, 7, 9]
Explanation: Column 0 holds 1 and 4, column 1 holds 2 and 5, and column 2 holds 3 and 6: 1 + 4 = 5, 2 + 5 = 7 and 3 + 6 = 9.

Example 2:

Input: grid = [[2, -1],
               [3, -1],
               [-5, 7]]
Output: [0, 5]
Explanation: Column 0 is 2 + 3 + (-5) = 0 and column 1 is -1 + (-1) + 7 = 5.

Example 3:

Input: grid = [[4, -2, 9]]
Output: [4, -2, 9]
Explanation: With one row, every column holds a single number, so each column's sum is that 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 7
    Ctrl + Enter to check

    TYPESCRIPT · NESTED LOOPS OVER GRIDS

    Column Sums in TypeScript, explained

    Problem overview

    The method columnSums receives grid, an array of rows (number[][]), and returns the sum of each column from left to right. Column c is made of the value at position c in every row. The grid has 1 to 10 rows and 1 to 10 values per row.

    For [[1, 2, 3], [4, 5, 6]] the columns are 1 and 4, 2 and 5, 3 and 6, so the result is [5, 7, 9]. For [[2, -1], [3, -1], [-5, 7]] it is [0, 5], and for a single row, [[4, -2, 9]], it is [4, -2, 9].

    Approach: make the column the outer loop

    A grid is stored as rows, so the natural loop for (const row of grid) hands over whole rows. A column is spread across all rows, one value in each. To collect it, the program needs the position of the column, so this lesson loops over indices instead of values.

    The outer loop picks a column number col, from left to right, which makes the sums come out in column order. The inner loop picks a row number row and reads grid[row][col]: grid[row] is a whole row, and [col] picks this column's value from it. When the inner loop ends, the column's total is complete.

    Step by step

    1. Create sums as an empty number[]. It collects one sum per column.
    2. Loop over the columns: for (let col = 0; col < grid[0].length; col++). Every row has one value per column, so the length of the first row is the number of columns.
    3. Create total at 0 inside the loop, so each column starts fresh.
    4. Loop over the rows: for (let row = 0; row < grid.length; row++). grid.length is the number of rows, and a column has one number in each.
    5. Add grid[row][col] to total.
    6. Push total onto sums after the inner loop, still inside the outer one.
    7. Return sums after both loops.

    The solution in TypeScript

    class Solution {
        columnSums(grid: number[][]): number[] {
            let sums: number[] = [];
            for (let col = 0; col < grid[0].length; col++) {
                let total = 0;
                for (let row = 0; row < grid.length; row++) {
                    total += grid[row][col];
                }
                sums.push(total);
            }
            return sums;
        }
    }
    

    Language details worth knowing:

    • Row first, then column. In grid[row][col] the first bracket picks a row and the second picks a position in it. Swapping them reads the wrong cell, and on a grid that isn't square it can reach a row that doesn't exist.
    • Reading past the end gives undefined. An array doesn't throw for a bad index. grid[0][5] on a three-column grid is undefined, and adding undefined to a number gives NaN. Reading a cell of a row that doesn't exist, such as grid[2][0] on a two-row grid, does throw, with a TypeError, because grid[2] is undefined.
    • let in for heads. let col = 0 declares a counter that belongs to the loop. col++ adds 1 after each pass.
    • .length is a property. It has no parentheses, for grid.length and grid[0].length alike.

    Complexity

    Time: O(R * C), one addition per cell. Space: O(C) for the result, one number per column.

    Edge cases and common mistakes

    • Swapped loop bounds. Using grid.length for the columns and grid[0].length for the rows works on a square grid and fails on a rectangular one. On [[1, 2, 3], [4, 5, 6]] the row loop would reach row 2, which doesn't exist, and the program would stop with a TypeError.
    • A single row. [[4, -2, 9]] returns [4, -2, 9]: each column holds one number.
    • Resetting total. It must be created inside the outer loop. Created before it, the sums would pile up from column to column.
    • Returning inside the outer loop. Only the first column's sum would come back.

    Testing

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