Start learning free

LESSON 259 OF 292 · NESTED LOOPS OVER GRIDS

Row Sums in Swift: One Total per Row

Practice Read the full explanation

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

    SWIFT · NESTED LOOPS OVER GRIDS

    Row Sums in Swift, explained

    Problem overview

    The method rowSums receives grid, an array of rows of integers, and returns an array holding the sum of each row, in the same order as the rows. A grid has between 1 and 10 rows, every row has the same number of values, and values may be negative.

    For [[1, 2, 3], [4, 5, 6]] the answer is [6, 15]. For [[-1, -2], [-3, -4], [5, 5]] it is [-3, -7, 10]: one sum per row, top to bottom, and a row of negative numbers has a negative sum. When every row holds a single value, as in [[3], [1], [4]], each row's sum is that value, so the answer is [3, 1, 4].

    Approach

    This is the grid sum from a different angle. Instead of one total for the whole grid, every row needs its own total, which is saved when the row is finished. The structure has three parts: an outer loop over the rows, a fresh total at the start of each row, and an inner loop that adds up that row's values.

    Where the total is created is the whole idea. If total were declared before the outer loop, it would keep growing across rows, and each saved number would include all the earlier rows. Declaring it inside the outer loop, before the inner one, resets it to 0 for every row.

    Step by step

    1. Create an empty result array. var sums = [Int]() starts with nothing and gets one number per row.
    2. Loop over the rows. for row in grid runs once per row, in order. Each row is an [Int].
    3. Start this row's total. Inside the loop, var total = 0 begins again for every row.
    4. Loop over the row's values. A second for value in row loop, still inside the outer one, visits only the current row.
    5. Add each value. total += value goes inside the inner loop.
    6. Save the row's sum. After the inner loop, but still inside the outer one, sums.append(total). At that moment the whole row has been added. Appending at the end of each pass keeps the sums in row order.
    7. Return sums after the outer loop. A return inside it would give back only the first row's sum.

    The solution in Swift

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

    Swift details worth knowing:

    • [Int]() builds an empty array of integers. It must be a var, since append changes the array. A let array can't be appended to, and the compiler says so.
    • Scope. total exists only inside the outer loop's braces. Each pass creates a new variable, which is why there is nothing to reset by hand.
    • Value semantics. The returned array is a separate value. Changing it later never changes grid.

    Complexity

    Time is O(r * c) for r rows and c columns, because each cell is added once. Space is O(r) for the result array, which holds one number per row.

    Edge cases and common mistakes

    • Total declared outside the outer loop. The sums become running totals. For [[1, 2, 3], [4, 5, 6]] the second entry would include the first row.
    • Appending in the wrong place. Putting sums.append(total) inside the inner loop adds a number per cell, not per row.
    • Appending after the outer loop. Only the last row's total would survive, and only once.
    • Single-column grids. [[3], [1], [4]] works unchanged: each inner loop runs once.
    • Negative sums. They are correct as they are, as in [-3, -7, 10].

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