Start learning free

LESSON 257 OF 285 · NESTED LOOPS OVER GRIDS

Grid Sum in Go: Nested Loops over a [][]int

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

    GO · NESTED LOOPS OVER GRIDS

    Grid Sum in Go, explained

    Problem overview

    The function gridSum receives grid, a slice of rows where each row is a slice of integers, and returns the sum of every number in it. Every row has the same number of values, and the numbers 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 for [[7]] it is 7.

    Approach: visit every cell once

    A grid in Go has the type [][]int: a slice whose elements are themselves slices of int. To touch every number you need two loops. The outer loop takes one row at a time. The inner loop takes the values of that row one at a time. Together they visit each cell exactly once, so adding each value to a running total gives the sum of the whole grid.

    The order of the visits does not matter for a sum, so there is no need to think about rows and columns separately. Later lessons use the same two loops but need to know where a value sits.

    Step by step

    1. Create total with := and start it at 0. It holds the sum of the numbers added so far.
    2. Loop over the rows: for _, row := range grid. Each row is a []int. The index is not needed, so _ discards it.
    3. Loop over the values of the row: for _, value := range row. For every row, this inner loop finishes all of its values before the outer loop moves on.
    4. Add the value: total += value.
    5. Return total after both loops. Returning inside a loop would add only part of the grid.

    The solution in Go

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

    Go details:

    • Two indexes give one value. For g := [][]int{{1, 2, 3}, {4, 5, 6}}, len(g) is 2 rows, len(g[0]) is 3 columns, and g[1][2] is 6: row 1, then column 2 of that row.
    • range copies the value. value is a copy of each element, which is fine for reading numbers. Assigning to it would not change the grid.
    • := declares and infers the type. total := 0 makes total an int, the same type as the grid's values.
    • += is shorthand for total = total + value.

    Edge cases and common mistakes

    • Negative numbers need no special handling. They simply make the total smaller, which is why [[-3, 4], [5, -6]] gives 0.
    • A single cell. [[7]] has one row with one value, so both loops run once and the result is 7.
    • Resetting the total inside a loop. If total := 0 sat inside the outer loop, each row would start over and the function would return only the last row's sum.
    • Returning too early. A return inside the loops would stop after the first cell.
    • Using one loop. A single loop over grid would give rows, not numbers, and total += row would not compile because a []int cannot be added to an int.

    Testing

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