Start learning free

LESSON 258 OF 285 · NESTED LOOPS OVER GRIDS

Row Sums in Go: One Total per Row of a Grid

Practice Read the full explanation

Given a grid of integers grid, return a slice with the sum of each row, in the same order as the rows.

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: [6, 15]
Explanation: Row 0 adds up to 1 + 2 + 3 = 6 and row 1 to 4 + 5 + 6 = 15.

Example 2:

Input: grid = [[-1, -2],
               [-3, -4],
               [5, 5]]
Output: [-3, -7, 10]
Explanation: One sum per row, top to bottom. A row of negative numbers has a negative sum.

Example 3:

Input: grid = [[3],
               [1],
               [4]]
Output: [3, 1, 4]
Explanation: Every row has a single value, so each row's sum is that value.

 

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

    Row Sums in Go, explained

    Problem overview

    The function rowSums receives grid, a [][]int, and returns a slice with the sum of each row, in the same order as the rows. The output has one number per row.

    For [[1, 2, 3], [4, 5, 6]] the answer is [6 15], since 1 + 2 + 3 = 6 and 4 + 5 + 6 = 15. For [[-1, -2], [-3, -4], [5, 5]] it is [-3 -7 10], and for the one-column grid [[3], [1], [4]] it is [3 1 4].

    Approach: one inner total per row

    Summing a whole grid needs one running total. Here every row needs its own. The outer loop visits the rows. For each row, a fresh total starts at 0, an inner loop adds that row's values to it, and when the inner loop finishes the total is appended to the result. Because rows are processed from top to bottom and each sum is appended once, the sums come out in row order.

    The important detail is where the total is created. It belongs inside the outer loop, so each row starts from 0 and one row's numbers never leak into the next sum.

    On the first example, sums is empty at the start, becomes [6] after the first row and [6 15] after the second. That final slice is the result.

    Step by step

    1. Create sums as an empty []int with :=. It collects one sum per row.
    2. Loop over the rows with for _, row := range grid.
    3. Create total at 0 inside that loop. It holds the current row's sum.
    4. Loop over the row's values with for _, value := range row.
    5. Add value to total.
    6. After the inner loop, append total to sums and assign the result back to sums. At this point the whole row has been added.
    7. Return sums after the outer loop. Returning inside it would send back only the first row's sum.

    The solution in Go

    func rowSums(grid [][]int) []int {
        sums := []int{}
        for _, row := range grid {
            total := 0
            for _, value := range row {
                total += value
            }
            sums = append(sums, total)
        }
        return sums
    }
    

    Go details:

    • append returns a slice, so sums = append(sums, total) must assign the result back. The slice may move to a larger array as it grows.
    • Scope. total is declared inside the outer loop's body, so it is created anew on every turn and is invisible after the loop ends. sums is declared outside, so it survives all the turns.
    • Printing. fmt.Println shows a slice of ints as [6 15], with spaces and no commas.
    • The empty slice literal []int{} is ready for append. A nil slice would work with append too.

    Edge cases and common mistakes

    • Declaring total outside the outer loop. The total then keeps growing across rows. With the declaration moved up, [[1, 2, 3], [4, 5, 6]] returns [6 21] instead of [6 15]: the second sum includes the first row.
    • Appending inside the inner loop. That would add one entry per cell instead of one per row.
    • One value per row. [[3], [1], [4]] gives [3 1 4]: each inner loop runs once.
    • Negative values. Rows of negative numbers give negative sums, as in -3 and -7 above.
    • Forgetting to assign the result of append. The compiler rejects an append whose result is unused.

    Testing

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