Start learning free

LESSON 259 OF 291 · NESTED LOOPS OVER GRIDS

Column Sums in Kotlin: Looping by Index over a Grid

Practice Read the full explanation

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

    KOTLIN · NESTED LOOPS OVER GRIDS

    Column Sums in Kotlin, explained

    Problem overview

    Given a grid of integers, return a list with the sum of each column, from left to right. The grid is an Array<IntArray>, with every row the same length. Column c is made of the value at position c in every row.

    For the rows [1, 2, 3] and [4, 5, 6] the columns hold 1 and 4, 2 and 5, and 3 and 6, so the result is [5, 7, 9]. For [2, -1], [3, -1] and [-5, 7] it is [0, 5]. A single row such as [4, -2, 9] gives [4, -2, 9], because each column holds just one number.

    Approach

    Rows are easy to reach: a grid is an array of rows, so a loop gives you each row in turn. Columns are not stored anywhere. A column is spread over all the rows, one value in each. To add up column c you must visit every row and pick the value at position c.

    That changes the order of the loops compared with row sums. The outer loop now picks the column, and the inner loop goes down the rows, adding grid[row][col]. Both loops use indexes, because you need the column number to pick a value out of each row.

    Step by step

    1. Create val sums = mutableListOf<Int>(), an empty list for one sum per column.
    2. Loop over the column numbers: for (col in 0 until grid[0].size). All rows have the same length, so the first row's size is the number of columns. Looping columns from left to right makes the sums come out in column order.
    3. Inside it, create var total = 0. It restarts at 0 for each column, so columns don't mix.
    4. Write a second loop over the row numbers: for (row in 0 until grid.size). A column has one value in every row, so this visits each row once.
    5. Add grid[row][col] to total. grid[row] is a whole row, and [col] picks this column's value out of it.
    6. After the inner loop, still inside the outer one, call sums.add(total). Every row's value for this column has been added by then.
    7. After both loops, return sums.

    The solution in Kotlin

    class Solution {
        fun columnSums(grid: Array<IntArray>): List<Int> {
            val sums = mutableListOf<Int>()
            for (col in 0 until grid[0].size) {
                var total = 0
                for (row in 0 until grid.size) {
                    total += grid[row][col]
                }
                sums.add(total)
            }
            return sums
        }
    }
    

    Some Kotlin details:

    • 0 until n covers 0 up to n - 1, exactly the valid indexes of an array of size n. Kotlin also offers grid.indices for the same range, which avoids writing the size.
    • For the first example, grid.size is 2 (the number of rows) and grid[0].size is 3 (the number of columns). Don't swap them: that mix-up is the most common mistake in this lesson.
    • grid[row][col] is two lookups: first the row array, then the value in it. Row comes first, column second.
    • Reading grid[0] on an empty array would throw an exception. The lesson guarantees at least one row, so it is safe here.

    Complexity

    Each cell is read once, so the time is O(r · c) for r rows and c columns. The result has c entries, so the extra space is O(c).

    Edge cases and common mistakes

    • Swapping the indexes. Writing grid[col][row] reads the wrong cells. For a grid that isn't square it fails with an ArrayIndexOutOfBoundsException, and for a square one it silently gives the row sums instead.
    • Wrong loop bounds. Using grid.size for the columns works only for square grids.
    • Total outside the outer loop. The sums would pile up from column to column.
    • One row. The inner loop runs once per column, so each column's sum is its single value.

    Testing

    • Rows [1, 2, 3] and [4, 5, 6] give [5, 7, 9].
    • Rows [2, -1], [3, -1] and [-5, 7] give [0, 5].
    • The single row [4, -2, 9] gives [4, -2, 9].
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free