Sum Each Row of a Grid
Practice 2D array basics: nested iteration and row/column indexing.
Given a 2D array grid of integers (a list of rows, where rows may have different lengths), return a 1D array where each element is the sum of the corresponding row in grid.
This is a basics exercise for 2D arrays/grids: the point is getting comfortable with nested iteration and grid[row][col]-style indexing, which shows up constantly in matrix and board problems.
Example 1
Input: grid = [[1,2,3],[4,5,6]]
Output: [6,15]
Explanation: Row 0 sums to 1+2+3=6, row 1 sums to 4+5+6=15.
Example 2
Input: grid = [[5]]
Output: [5]
Example 3
Input: grid = [[]]
Output: [0]
Explanation: A row with no elements sums to 0.
Constraints
- 0 <= grid.length <= 100
- 0 <= grid[i].length <= 100
- -1000 <= grid[i][j] <= 1000
Follow-up
How would you compute the sum of each column instead? Does your approach still work if rows have different lengths?
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
No test cases yet.