Problem overview
The method gridSum receives grid, a table of integers stored as a list of rows, where each row is itself a list. It returns the sum of every number in the table. Rows are counted from the top and columns from the left, both starting at 0, and every row has the same number of values.
For [[1, 2, 3], [4, 5, 6]] the first row adds up to 6 and the second to 15, so the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, because negative numbers simply make the sum smaller. A grid with one cell, [[7]], gives 7.
Approach: one loop per level
A grid has two levels. The outer list holds rows, and each row holds numbers. Visiting every number therefore takes two loops, one inside the other. The outer loop picks a row; the inner loop goes through that row's values before the outer loop moves on. Together the loops visit every cell exactly once, and each value is added to a running total.
You never need to know how many rows or columns there are. Looping directly over the items, rather than over indexes, lets Python handle the sizes.
Step by step
- Create
totaland set it to 0. No number has been added yet. - Loop
rowovergrid. Each item ofgridis a list of integers, sorowis a whole row. - Inside it, loop
valueoverrow. For every row, this inner loop visits all its values. - Add
valuetototalin the inner loop body. - Return
totalafter both loops. Returning inside a loop would stop after the first value or the first row.
The solution in Python
class Solution:
def gridSum(self, grid: List[List[int]]) -> int:
total = 0
for row in grid:
for value in row:
total += value
return total
Python details:
- Indentation shows nesting. The line
total += valueis indented under the innerfor, which is indented under the outer one. Moving thereturnto the same indentation asfor rowputs it after both loops. total += valueis shorthand fortotal = total + value.- Integers don't overflow. Python integers grow as needed, so a big sum is not a concern here (the values are small anyway).
Python offers shorter forms once the loops are clear. sum(map(sum, grid)) sums each row and then the row sums, and for [[1, 2, 3], [4, 5, 6]] it also gives 21. The nested loop spells out what those calls do.
Edge cases and common mistakes
- Resetting
totalin the wrong place. Iftotal = 0were inside the outer loop, it would restart for every row and the function would return only the last row's sum. - Returning too early. A
returninside the inner loop gives the first value; inside the outer loop it gives the first row's sum. - Looping over the wrong thing.
for value in gridgives rows, not numbers, and adding a list to an integer raises aTypeError. - Single cell and negatives.
[[7]]works with no special case, and negative values are added like any others.
Testing
[[1, 2, 3], [4, 5, 6]]gives21.[[-3, 4], [5, -6]]gives0.[[7]]gives7.
