Start learning free

LESSON 256 OF 671 · NESTED LOOPS OVER GRIDS

Column Sums in JavaScript: Index Loops Over a Grid

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

    JAVASCRIPT · NESTED LOOPS OVER GRIDS

    Column Sums in JavaScript, explained

    Problem overview

    The method columnSums(grid) receives a grid of integers, an array of rows, and returns an array with the sum of each column, from left to right. Column c is made of the value at position c in every row.

    For [[1, 2, 3], [4, 5, 6]], column 0 holds 1 and 4, column 1 holds 2 and 5, and column 2 holds 3 and 6, so the result is [5, 7, 9]. For [[2, -1], [3, -1], [-5, 7]] the result is [0, 5]. For a single row, [[4, -2, 9]], each column holds one number, so the result is [4, -2, 9].

    Approach

    Row sums are easy because a grid is stored as rows: for...of hands you one row at a time. Columns aren't stored anywhere. A column exists only as the value at the same position in every row, so you have to pick it out yourself with indices.

    That changes the loop order. The outer loop goes over column numbers, col, from 0 to the last column. For each column the inner loop goes over row numbers, row, and adds grid[row][col]: the first index picks the row, the second picks the position inside it. Because the outer loop moves left to right, the sums come out in column order.

    How many columns are there? Every row has one value per column, so the length of the first row, grid[0].length, is the number of columns. The number of rows is grid.length.

    Step by step

    1. Create sums as an empty array. One sum per column will be added to it.
    2. Loop over the columns. for (let col = 0; col < grid[0].length; col++) visits each column number, left to right.
    3. Create total inside that loop, at 0. It restarts for every column, so one column's numbers never mix into the next.
    4. Loop over the rows. for (let row = 0; row < grid.length; row++): a column has one number in every row, so the inner loop visits each row once.
    5. Add the cell. total += grid[row][col]. Here grid[row] is a whole row, and [col] picks this column's number out of it.
    6. Push the total after the inner loop, still inside the outer one. Every row's number in this column has been added by then.
    7. Return sums after both loops.

    The solution in JavaScript

    class Solution {
        columnSums(grid) {
            let sums = [];
            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;
        }
    }
    

    Details worth knowing:

    • Index order is [row][col]. grid[1][2] is row 1, column 2. For [[1, 2, 3], [4, 5, 6]] that is 6.
    • The condition is re-evaluated on every turn. col < grid[0].length reads the length each time. That is cheap and works fine. Storing it in a variable first is also fine.
    • Reading past the end gives undefined. grid[5] on a two-row grid is undefined, and indexing into it throws a TypeError. JavaScript doesn't stop you from using a wrong bound.

    Complexity

    Time: O(r × c) for r rows and c columns. The two loops together touch each cell once.

    Space: O(c) for the result, one number per column.

    Edge cases and common mistakes

    • Swapping the bounds. If the outer loop runs to grid.length and the inner to grid[0].length, the loops work for a square grid but not for others. On [[1, 2, 3], [4, 5, 6]] the inner loop reaches row 2, which doesn't exist, and the program throws TypeError: Cannot read properties of undefined (reading '0').
    • Swapping the indices. grid[col][row] reads the cells in the wrong places. The first index is always the row.
    • Not resetting total. It must be created inside the outer loop, or each column's sum would include the earlier columns.
    • One row. [[4, -2, 9]] gives [4, -2, 9]: each inner loop runs once.
    • One column. The outer loop runs once and the result has a single number, the sum of the whole column.

    Testing

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