Start learning free

LESSON 256 OF 671 · NESTED LOOPS OVER GRIDS

Column Sums in Java: Index Loops over an int[][]

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

    JAVA · NESTED LOOPS OVER GRIDS

    Column Sums in Java, explained

    Problem overview

    Given a grid grid of type int[][], columnSums returns a list with the sum of each column, from left to right. Every row has the same number of values, and rows and columns are counted from 0. Column c is made of the value at position c in every row.

    For [[1, 2, 3], [4, 5, 6]] the result is [5, 7, 9]: column 0 holds 1 and 4, column 1 holds 2 and 5, and column 2 holds 3 and 6. For [[2, -1], [3, -1], [-5, 7]] it is [0, 5]. For a single row such as [[4, -2, 9]], every column holds one number, so the result is [4, -2, 9].

    Approach

    Summing rows is easy in Java because an int[][] is an array of rows: a for-each loop hands you one row at a time. Columns have no such shortcut. There is no object that is "column 1"; a column is spread across the rows, one value from each. So the loops need numbers, not just values.

    The plan is to loop over column numbers on the outside and row numbers on the inside. For a fixed column col, the inner loop visits grid[row][col] for every row and adds them up. Looping over columns first means one column is finished before the next starts, so the sums are saved in left-to-right order.

    Step by step

    1. Create sums, an empty List<Integer> backed by a new ArrayList. It will collect one sum per column.
    2. Write a for loop with an int col from 0 while col < grid[0].length. Every row has one value per column, so the length of the first row is the number of columns.
    3. Inside it, create an int named total starting at 0. It is created again for each column, so the columns' numbers never mix.
    4. Below that, write an inner for loop with an int row from 0 while row < grid.length, the number of rows. A column has one number in every row, so this loop visits each row once.
    5. Inside the inner loop, add grid[row][col] to total. The expression grid[row] is a whole row, and [col] then picks this column's number out of it.
    6. After the inner loop, still inside the outer one, call sums.add(total). Every row's number in this column has been added, so total is the column's sum.
    7. After both loops, return sums.

    Tracing the first example

    For [[1, 2, 3], [4, 5, 6]], grid.length is 2 and grid[0].length is 3. The outer loop runs for col 0, 1 and 2. For col = 0, the inner loop adds grid[0][0] and grid[1][0], which are 1 and 4. The other two columns work the same way, and the method returns [5, 7, 9].

    The solution in Java

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

    Java details in this code:

    • Row first, then column. grid[row][col] is always written row index first. grid.length counts rows, and grid[0].length counts the values in the first row, which is the number of columns.
    • length has no parentheses on arrays. It is a field, so it is grid.length, not grid.length(). A List uses size() instead.
    • Out-of-range indexes throw. Java doesn't wrap or ignore a bad index: it throws ArrayIndexOutOfBoundsException. With a grid whose rows differ in length, such as {{1, 2}, {3}}, this method fails with "Index 1 out of bounds for length 1". The lesson guarantees equal rows, so it doesn't come up.
    • The imports. List and ArrayList are in java.util: a standalone program needs import java.util.*;.

    Complexity

    With R rows and C columns, the inner loop body runs R times for each of the C columns, so every cell is visited once: O(R * C) time. The result list holds C numbers, so the extra space is O(C).

    Edge cases and common mistakes

    • Swapping the indexes. Writing grid[col][row] reads the grid transposed. For the 2 by 3 grid [[1, 2, 3], [4, 5, 6]] it throws "Index 2 out of bounds for length 2", because col reaches 2 and there are only two rows. In a square grid it wouldn't crash and would silently return the row sums instead.
    • Using grid.length as the column count. That is the number of rows. The two are equal only in a square grid.
    • Declaring total outside the outer loop. Each column's total would start from the previous one.
    • A single row. [[4, -2, 9]] gives [4, -2, 9]: the inner loop runs once per column, and each sum is that one number.
    • Negative values. They simply lower the sums. Column 0 of the second example is 2 + 3 + (-5), which is 0.

    Testing

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