Start learning free

LESSON 258 OF 289 · NESTED LOOPS OVER GRIDS

Column Sums in C#: Indexed Loops over an int[][]

Practice Read the full explanation

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

    C# · NESTED LOOPS OVER GRIDS

    Column Sums in C#, explained

    Problem overview

    ColumnSums receives grid, an int[][], and returns a List<int> with the sum of each column, from left to right. Column c is made of the value at position c in every row.

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

    Approach: columns on the outside

    A jagged array is a list of rows, so rows are easy to reach: foreach gives them one at a time. Columns are not stored anywhere. To sum a column you must reach into every row at the same position. That needs indexes, so this lesson swaps foreach for for loops.

    The nesting is the reverse of Row Sums. The outer loop picks a column, and the inner loop walks down the rows, adding the value where that row meets the column. When the inner loop ends, the column is complete. Because the outer loop goes through the columns from left to right, the sums come out in column order.

    Step by step

    1. Create an empty List<int> named sums. It collects one sum per column.
    2. Loop over column numbers with for (int col = 0; col < grid[0].Length; col++). Every row has one value per column, so the length of the first row, grid[0].Length, is the number of columns.
    3. Create int total = 0 inside the loop. It starts again at 0 for every column, so one column's numbers never mix into the next.
    4. Write the inner loop over row numbers: for (int row = 0; row < grid.Length; row++). grid.Length is the number of rows, and a column has one number in each.
    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, sums.Add(total). Every row's number in this column has been added by then.
    7. Return sums after the outer loop, not inside it, or only the first column would come back.

    The solution in C#

    class Solution {
        public List<int> ColumnSums(int[][] grid) {
            List<int> sums = new List<int>();
            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;
        }
    }
    

    C# details:

    • Row first, then column. In grid[row][col] the first brackets pick a row (an int[]) and the second pick a position in it. Swapping them reads the wrong cell, and on a grid that is not square it can go out of range.
    • Out of range throws. Reading grid[3][0] on a grid with three rows throws IndexOutOfRangeException. Arrays are checked on every access, so a wrong bound crashes loudly instead of reading garbage.
    • The first row sets the width. grid[0].Length is safe here because the grid always has at least one row. On an empty array of rows (new int[0][]), grid[0] itself throws IndexOutOfRangeException.
    • Length versus Count. Arrays have Length; a List<int> has Count. The grid is made of arrays, so the loops use Length.
    • List<T> lives in System.Collections.Generic; in a file of your own, add using System.Collections.Generic;.

    Edge cases and common mistakes

    • Mixing up the two bounds. The columns loop is bounded by grid[0].Length and the rows loop by grid.Length. Using one for both only works on square grids and fails on, say, 2 rows by 3 columns.
    • Not resetting total. Declared before the outer loop, it would carry each column's sum into the next.
    • One row. The inner loop runs once per column, so each sum is that single value.
    • Negative values. [[2, -1], [3, -1], [-5, 7]] gives [0, 5], so a column can sum to 0.

    Testing

    gridResult
    [[1, 2, 3], [4, 5, 6]][5, 7, 9]
    [[2, -1], [3, -1], [-5, 7]][0, 5]
    [[4, -2, 9]][4, -2, 9]
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free