Start learning free

LESSON 260 OF 292 · NESTED LOOPS OVER GRIDS

Column Sums in Swift: Looping by Index

Practice Read the full explanation

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

    SWIFT · NESTED LOOPS OVER GRIDS

    Column Sums in Swift, explained

    Problem overview

    The method columnSums receives grid, an array of rows of integers, and returns an array with the sum of each column, from left to right. Column c is made of the value at position c in every row. Every row has the same number of values.

    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, column 2 holds 3 and 6. For [[2, -1], [3, -1], [-5, 7]] it is [0, 5]. With a single row, [[4, -2, 9]], every column holds one number, so the answer is [4, -2, 9].

    Approach

    Looping with for row in grid walks a grid row by row, which suits row sums. A column cuts across the rows, so the loops change roles. The outer loop now picks a column number, and the inner loop goes down through the rows, adding the value where that row meets the column.

    That needs indexes rather than values. The number of columns is the length of any row; since all rows have the same length, grid[0].count is the number of columns. The number of rows is grid.count. The cell in row row and column col is grid[row][col]: grid[row] is a whole row, and [col] picks one number out of it.

    As in the row version, the total is created inside the outer loop, so each column starts from 0.

    Step by step

    1. Create an empty result array sums with var. It collects one sum per column.
    2. Loop over the column indexes. for col in 0..<grid[0].count goes from the leftmost column to the rightmost, so the sums come out in column order.
    3. Start this column's total with var total = 0, inside the loop.
    4. Loop over the row indexes. for row in 0..<grid.count visits every row once, because a column has one number in each.
    5. Add the cell. total += grid[row][col] reads row row at column col.
    6. Save the column's sum. After the inner loop, sums.append(total).
    7. Return sums after the outer loop.

    The solution in Swift

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

    Swift details worth knowing:

    • Half-open ranges. 0..<n runs from 0 up to n - 1, which matches array indexes exactly. 0...n would include n, one past the end, and the program would crash with an index-out-of-range error.
    • Why grid[0] is safe. The lesson guarantees at least one row. On an empty array, grid[0] would crash at run time, because Swift checks every array index.
    • Two subscripts. grid[row][col] is two reads: first an [Int], then an Int from it.
    • Loop variables. col and row are new constants on each turn, so they can't be assigned to.

    Complexity

    Time is O(r * c): the two loops together touch each cell once, even though the order is column by column. Space is O(c) for the result, one number per column.

    Edge cases and common mistakes

    • Swapping the indexes. Writing grid[col][row] reads the wrong cell. It crashes when the grid isn't square, because a column number is then used as a row number.
    • Wrong bounds. Using grid.count for the outer loop gives the number of rows, not columns. For a grid with 2 rows and 3 columns this would produce too few sums.
    • Total outside the loop. Each column's sum would include all the columns before it.
    • One row. [[4, -2, 9]] returns the row itself, because each column holds one number.
    • One column. The result has one element, the sum of every row's only value.

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