Row Aggregates
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
Problem
Given a 2D matrix of numbers, return a list where each element is the sum of the corresponding row.
Each row holds its own summary.
Example 1
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:
[6,15,24]
Example 2
Input:
matrix = [[10,20],[30,40]]
Output:
[30,70]
Worked solution and explanation
Why this problem exists in real interviews
Summing each row of a matrix tests basic nested iteration and whether you can map a 2D structure to a 1D result. It is the Python equivalent of a GROUP BY with SUM.
Break down the requirements
Step 1: Iterate over each row
Each row is a list of numbers within the matrix.
Step 2: Sum the elements of each row
Accumulate the row total and add it to the result list.
The solution
def row_sums(matrix):
result = []
for row in matrix:
total = 0
for val in row:
total += val
result.append(total)
return resultCommon follow-up questions
- How would you compute column sums instead? (Tests transposing the iteration: iterate column indices in the outer loop, rows in the inner.)
- What if the matrix is ragged (rows of different lengths)? (Tests that the inner loop naturally handles variable-length rows.)
- How would you compute row averages? (Tests dividing each sum by the row length, with a zero-length guard.)