Start learning free

LESSON 255 OF 671 · NESTED LOOPS OVER GRIDS

Row Sums in Java: One Total per Row of an int[][]

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

    JAVA · NESTED LOOPS OVER GRIDS

    Row Sums in Java, explained

    Problem overview

    Given a grid grid of type int[][], rowSums returns a list with the sum of each row, in the same order as the rows. The grid is a table of numbers where every row has the same number of values, and rows are counted from the top, starting at 0.

    For [[1, 2, 3], [4, 5, 6]] the result is [6, 15]: row 0 adds up to 1 + 2 + 3 and row 1 to 4 + 5 + 6. For [[-1, -2], [-3, -4], [5, 5]] it is [-3, -7, 10]. For [[3], [1], [4]], where every row has a single value, it is [3, 1, 4].

    Approach

    Summing a whole grid needs one running total. Here the answer is a list of totals, one per row, so each row needs its own total that starts fresh. The pattern is:

    1. Go through the rows one at a time.
    2. For each row, start a total at 0 and add the row's values to it.
    3. When the row is finished, save its total in the result list.

    Because the outer loop takes the rows from the top down and each total is saved as soon as its row ends, the sums come out in row order with no extra work.

    Step by step

    1. Create sums, an empty List<Integer> backed by a new ArrayList. The sums go in one at a time, so it starts empty.
    2. Write a for-each loop with an int[] named row over grid. Each row gives exactly one sum, so the loop runs once per row.
    3. Inside it, create an int named total starting at 0. Because it is created inside the outer loop, it starts again at 0 for every row, and one row's numbers never mix into the next row's sum.
    4. Below that, still in the outer loop, write an inner for-each loop with an int named value over row. It visits the values of the current row only.
    5. Inside the inner loop, add value to total.
    6. After the inner loop but still inside the outer one, call sums.add(total). At that point the whole row has been added, so total is this row's sum.
    7. After both loops, return sums. Returning inside the outer loop would hand back only the first row's sum.

    Tracing the second example

    For [[-1, -2], [-3, -4], [5, 5]], the first row gives -3, the second -7 and the third 10. Each total is added to sums right after its row is done, and the method returns [-3, -7, 10].

    The solution in Java

    class Solution {
        public List<Integer> rowSums(int[][] grid) {
            List<Integer> sums = new ArrayList<>();
            for (int[] row : grid) {
                int total = 0;
                for (int value : row) {
                    total += value;
                }
                sums.add(total);
            }
            return sums;
        }
    }
    

    Java details in this code:

    • Where a variable is declared decides its lifetime. total exists only inside the body of the outer loop. Each turn creates a new one, set to 0, and it disappears at the closing brace. That is exactly the "fresh total per row" behaviour the problem needs, without a line that resets it.
    • List<Integer>, not List<int>. Collections hold objects, so the element type is the wrapper Integer. Java boxes the int automatically in sums.add(total).
    • Interface on the left. The variable is declared as List, and the object created is an ArrayList. The method's return type is List<Integer> as well.
    • The imports. List and ArrayList live in java.util, so a standalone program needs import java.util.*;.
    • Printing. A list prints as [6, 15], with square brackets and commas.

    Edge cases and common mistakes

    • Declaring total outside the outer loop. The first row would add up correctly, but the second row's total would start from the first row's. For the first example you would get [6, 21] instead of [6, 15].
    • Adding to sums inside the inner loop. That adds a running total after every value, so the list would have one entry per cell instead of one per row.
    • Adding to sums after the outer loop. Only the last row's total would be saved, and only one number would come back.
    • Single-value rows. Each sum equals the value itself, as in [[3], [1], [4]]. The same code handles this.
    • Negative values. They make a row's sum smaller, and can make it negative. Nothing special is needed.

    Testing

    • rowSums(new int[][]{{1, 2, 3}, {4, 5, 6}}) returns [6, 15].
    • rowSums(new int[][]{{-1, -2}, {-3, -4}, {5, 5}}) returns [-3, -7, 10].
    • rowSums(new int[][]{{3}, {1}, {4}}) returns [3, 1, 4].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free