# Row Aggregates

> Each row holds its own summary.

Canonical URL: <https://datadriven.io/problems/row_aggregates>

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.

## 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

**Row-wise summation with nested iteration**

```python
def row_sums(matrix):
    result = []
    for row in matrix:
        total = 0
        for val in row:
            total += val
        result.append(total)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(r * c) where r is the number of rows and c is the number of columns.
> 
> **Space:** O(r) for the result list.

> **Interviewers Watch For**
>
> Clean nested loops rather than flattening the matrix. The two-level structure directly maps to the row-aggregation task.

> **Common Pitfall**
>
> Using `sum(row)` is fine in production but may be disallowed in an interview that asks you to implement the aggregation manually.

---

## Common 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.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/row_aggregates)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.