Problem overview
Given a grid grid of type int[][], gridSum returns the sum of all its numbers. A grid is a table made of rows, each row has the same number of values, and rows and columns are counted from 0.
For [[1, 2, 3], [4, 5, 6]] the first row adds up to 6, the second to 15, and the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, because negative numbers simply make the sum smaller. For [[7]] the answer is 7.
Approach
In Java, an int[][] is an array of arrays. Each item of grid is a row, and each row is itself an int[]. So there are two levels to walk through: first pick a row, then pick each value in it.
That is a pair of nested loops. The outer loop runs once per row. For each row, the inner loop visits every value in it before the outer loop moves on. Together they visit every cell exactly once, which is what a sum over the whole grid needs. One variable, total, collects the numbers as they go by.
Step by step
- Create an
intnamedtotaland start it at 0. No number has been added yet, so the sum starts at 0. - Write a for-each loop with an
int[]namedrowovergrid. The type of the loop variable isint[], notint, because each item of anint[][]is a whole row. - Inside it, write a second for-each loop with an
intnamedvalueoverrow. For every row, this loop visits all of its values before the outer loop continues. - Inside the inner loop, add
valuetototalwith+=. - After both loops, return
total. Areturninside the loops would stop after part of the grid.
Tracing the first example
For [[1, 2, 3], [4, 5, 6]], the outer loop first gives row = [1, 2, 3]. The inner loop adds 1, 2 and 3, so total is 6. The outer loop then gives row = [4, 5, 6], and the inner loop adds 4, 5 and 6, which brings total to 21. Both loops end, and the method returns 21.
The solution in Java
class Solution {
public int gridSum(int[][] grid) {
int total = 0;
for (int[] row : grid) {
for (int value : row) {
total += value;
}
}
return total;
}
}
Java details in this code:
- The loop variable's type. In
for (int[] row : grid),rowhas typeint[]. Writingfor (int row : grid)would not compile, because anint[]can't be stored in anint. - Rows are shared, not copied.
rowrefers to the same array that lives insidegrid. This code only reads it, so that doesn't matter here. If a loop assigned torow[0], the grid would change. - For-each has no index. The loops give values without telling you the row or column number. For this task that is fine, since the position of a number doesn't affect the sum. Problems that need positions use ordinary
forloops with indexes. - Rows can differ in length in Java. An
int[][]can hold rows of different sizes. The lesson guarantees the same size in every row, and the for-each version works either way, because each inner loop uses its own row's length.
Edge cases and common mistakes
- Negative values. Adding a negative number lowers the total. For
[[-3, 4], [5, -6]],-3 + 4 + 5 - 6gives 0. Nothing special is required. - A single cell.
[[7]]has one row with one value, and each loop runs once. The result is 7. - Returning too early. Putting
return total;inside a loop returns after the first row or the first value. - Resetting the total. If
totalis declared inside the outer loop, it starts over at 0 for every row and the method sums only the last row. It has to be declared before both loops. - Mixing up the loop types. The inner loop goes over
row, notgrid. Looping overgridagain would give you rows, not numbers.
Testing
gridSum(new int[][]{{1, 2, 3}, {4, 5, 6}})returns 21.gridSum(new int[][]{{-3, 4}, {5, -6}})returns 0.gridSum(new int[][]{{7}})returns 7.
