# The Rolling Window

> Smooth things out, one step at a time.

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

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Given a list of numbers and positive integer k, compute the average of every contiguous window of size k. Return the list of averages (one per window) rounded to 2 decimals. If len(nums) < k, return an empty list.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests the **sliding window pattern** for computing moving averages, a ubiquitous operation in time-series analysis and monitoring. It checks whether candidates use an O(n) approach instead of O(n * k) recomputation.

---

### Break down the requirements

#### Step 1: Compute the sum of the first window

Sum the first k elements.

#### Step 2: Slide the window across the array

For each new position, subtract the element leaving and add the element entering. Compute and store the average.

#### Step 3: Round each average to 2 decimal places

Use Python's `round()` to format the output.

---

### The solution

**Sliding window with running sum for moving average**

```python
def moving_average(nums, k):
    result = []
    window_sum = 0
    for i in range(k):
        window_sum += nums[i]
    result.append(round(window_sum / k, 2))
    for i in range(k, len(nums)):
        window_sum += nums[i] - nums[i - k]
        result.append(round(window_sum / k, 2))
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) with a single pass.
> 
> **Space:** O(n - k + 1) for the output list.

> **Interviewers Watch For**
>
> Do you use a running sum? The naive approach of summing k elements for each window is O(n * k). Incremental updates reduce this to O(n).

> **Common Pitfall**
>
> Floating-point precision accumulation. After many additions and subtractions, the running sum may drift slightly. For most practical purposes this is acceptable, but mentioning it shows awareness.

---

## Common follow-up questions

- What if you needed the moving median instead of average? _(Tests sorted container or two-heap approaches for O(k log k) per window.)_
- What if the window size exceeded the array length? _(Tests returning an empty list or raising an error.)_
- How would you compute this on a streaming input? _(Tests maintaining a deque buffer of size k.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_rolling_window)
- [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.