Start learning free

LESSON 258 OF 291 · NESTED LOOPS OVER GRIDS

Row Sums in Kotlin: One Sum per Row of a Grid

Practice Read the full explanation

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

    KOTLIN · NESTED LOOPS OVER GRIDS

    Row Sums in Kotlin, explained

    Problem overview

    Given a grid of integers, return a list holding the sum of each row, in row order. The grid is an Array<IntArray>: an array of rows, where every row has the same number of values and rows are counted from 0 at the top.

    For the rows [1, 2, 3] and [4, 5, 6] the result is [6, 15]. For [-1, -2], [-3, -4] and [5, 5] it is [-3, -7, 10]: a row of negative numbers has a negative sum. When every row has one value, as in [3], [1] and [4], the sums are those values: [3, 1, 4].

    Approach

    This differs from adding up the whole grid in one way: there is one answer per row, not one overall. So the running total must start from 0 again for each row, and when a row is finished its total goes into the result list. An outer loop walks the rows and an inner loop adds up the current row.

    Step by step

    1. Create val sums = mutableListOf<Int>(), an empty list that will collect one sum per row. It starts empty because the sums arrive one at a time.
    2. Write for (row in grid). Each run of the loop body handles one row.
    3. Inside it, create var total = 0. Declaring it inside the outer loop gives each row a fresh total, so one row's numbers are never mixed into the next row's sum.
    4. Write for (value in row), which visits the values of the current row only, and total += value inside it.
    5. After the inner loop, but still inside the outer one, call sums.add(total). The whole row has been added by then. Adding at this point also keeps the sums in row order.
    6. After the outer loop, return sums. Returning inside the loop would return only the first row's sum.

    The solution in Kotlin

    class Solution {
        fun rowSums(grid: Array<IntArray>): List<Int> {
            val sums = mutableListOf<Int>()
            for (row in grid) {
                var total = 0
                for (value in row) {
                    total += value
                }
                sums.add(total)
            }
            return sums
        }
    }
    

    Some Kotlin details:

    • The function returns List<Int>, while the list you build is a MutableList<Int>. That is allowed, because a mutable list is also a list. The caller just can't change it through the List type.
    • val sums means the variable always refers to the same list. The list still grows with add.
    • The position of var total = 0 matters. A variable declared inside a loop body exists only for one run of that body, so each row gets a new total. It also isn't visible after the loop.
    • Printing a list of ints shows [6, 15].

    Complexity

    Every cell is visited once, so for a grid with r rows and c columns the time is O(r · c). The result list has r entries, so the extra space is O(r).

    Edge cases and common mistakes

    • Declaring total outside the outer loop. The sums would then be cumulative: for the first example the result would be [6, 21] instead of [6, 15].
    • Adding to sums inside the inner loop. You would get one entry per cell, not per row.
    • Adding after the outer loop. Only the last row's total would exist by then, and only once.
    • One column. A grid like [[3], [1], [4]] needs no special case: each inner loop runs once.

    Testing

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