Start learning free

LESSON 258 OF 292 · NESTED LOOPS OVER GRIDS

Grid Sum in Swift: Nested for-in Loops

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

    SWIFT · NESTED LOOPS OVER GRIDS

    Grid Sum in Swift, explained

    Problem overview

    The method gridSum receives grid, an array of rows where each row is an array of integers, and returns the sum of every number in it. All rows have the same length. The values 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, because the negative numbers cancel the positive ones. A grid with one cell, [[7]], gives 7.

    Approach

    A grid is an array of arrays, so reaching every cell takes two loops, one inside the other. The outer loop picks a row. The inner loop walks through the values of that row. Together they visit each cell exactly once, and a running total collects the values.

    The type [[Int]] explains why this works. Looping over a [[Int]] hands out its elements, and each element is an [Int]: a whole row. Looping over that row hands out plain Int values. There is no index arithmetic to get wrong.

    Step by step

    1. Create total with var, starting at 0. No number has been added yet, so 0 is the right start, and var is needed because the value changes.
    2. Loop over the rows. for row in grid runs once per row, from the top one down. Close the loop's brace right away and put the next step inside it.
    3. Loop over the values of the row. for value in row sits inside the first loop. For every row, it runs through all of that row's values before the outer loop moves on.
    4. Add the value. total += value goes inside the inner loop, so every cell is added once, negative ones included.
    5. Return total after both loops. Returning inside a loop would add only part of the grid.

    The solution in Swift

    class Solution {
        func gridSum(_ grid: [[Int]]) -> Int {
            var total = 0
            for row in grid {
                for value in row {
                    total += value
                }
            }
            return total
        }
    }
    

    Swift details worth knowing:

    • Loop variables are constants. row and value are fresh constants on every turn. You can read them but not assign to them.
    • [[Int]] is an array of arrays. Arrays are value types, so row is a copy of the row, taken cheaply because Swift copies the storage only if someone modifies it. Nothing in this loop changes grid.
    • Int is 64 bits. With values between -1000 and 1000 and at most 100 cells, the sum is far from overflowing. Swift traps on overflow instead of wrapping, but it is not a concern here.

    Complexity

    Time is O(r * c) for a grid with r rows and c columns: one addition per cell. Space is O(1), because only total is stored besides the input.

    Edge cases and common mistakes

    • Single cell. [[7]] runs each loop once and returns 7.
    • Negative values. They are added like any other number. [[-3, 4], [5, -6]] gives 0.
    • Returning too early. A return total inside either loop adds only the first cell or the first row instead of the whole grid.
    • Declaring total inside a loop. It would start again at 0 on every row, and the final value would be out of scope for the return.
    • Using one loop. for value in grid hands out rows, not numbers, so total += value is a type error: an [Int] can't 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 Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free