Start learning free

LESSON 259 OF 285 · NESTED LOOPS OVER GRIDS

Column Sums in Go: Indexing a [][]int by Column

Practice Read the full explanation

Given a grid of integers grid, return a slice 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

    GO · NESTED LOOPS OVER GRIDS

    Column Sums in Go, explained

    Problem overview

    The function columnSums receives grid, a [][]int where every row has the same number of values, and returns a slice 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]] the answer is [5 7 9]: column 0 holds 1 and 4, column 1 holds 2 and 5, and column 2 holds 3 and 6. For [[2, -1], [3, -1], [-5, 7]] it is [0 5], and for the single row [[4, -2, 9]] it is [4 -2 9].

    Approach: loop over column numbers, then rows

    Summing rows is easy because a row is already a slice you can range over. A column is not stored anywhere as a unit: it is spread across all the rows. To read column col you visit every row and take grid[row][col].

    So the loops swap roles compared with row sums. The outer loop runs over column numbers, left to right. For each column, a fresh total starts at 0 and the inner loop runs over the row numbers, adding grid[row][col]. When the inner loop ends, the total is that column's sum and goes into the result. Because the outer loop moves left to right, the sums come out in column order.

    Step by step

    1. Create sums as an empty []int with :=.
    2. Loop over column numbers: for col := 0; col < len(grid[0]); 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 row numbers: for row := 0; row < len(grid); row++. A column has one number in every row.
    5. Add grid[row][col] to total. The first index picks the row, the second picks the column inside it.
    6. After the inner loop, append total to sums and assign the result back.
    7. Return sums after both loops.

    The solution in Go

    func columnSums(grid [][]int) []int {
        sums := []int{}
        for col := 0; col < len(grid[0]); col++ {
            total := 0
            for row := 0; row < len(grid); row++ {
                total += grid[row][col]
            }
            sums = append(sums, total)
        }
        return sums
    }
    

    Go details:

    • Index loops instead of range. Here the loops need the numbers row and col themselves, to build grid[row][col], so they use the classic three-part for. The loop variable lives only inside its loop.
    • Row first, column second. In grid[row][col], grid[row] is a whole []int, and [col] then picks one element of it. Swapping the two indexes reads a different cell, and may be out of range.
    • Out-of-range indexes panic. Go checks every index at run time and stops the program with an error such as index out of range [0] with length 0. That is what grid[0] does on an empty grid, which the lesson's constraints rule out by promising at least one row.
    • Printing. A slice of ints prints as [5 7 9].

    Edge cases and common mistakes

    • Using len(grid) for the columns. len(grid) is the number of rows. For a grid with 2 rows and 3 columns, looping col up to len(grid) would skip a column. In a grid with more rows than columns it would run past the end of each row and panic.
    • Mixing up the indexes. Writing grid[col][row] reads the transposed cell. It looks right on a square grid and fails on others.
    • Moving total outside the outer loop. Each column's sum would then include the columns before it.
    • One row. [[4, -2, 9]] gives [4 -2 9]: every inner loop runs once.
    • Negative numbers. Column 0 of [[2, -1], [3, -1], [-5, 7]] is 2 + 3 + (-5) = 0.

    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 Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free