# The Forward Fill

> Patch the gaps in a noisy sensor stream.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a list that may contain None values, return a list of the same length where each None is replaced by the most recent prior non-None value. If a None appears before any non-None value has been seen, leave it as None.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **forward fill imputation**, a critical time-series data cleaning pattern. It probes whether a candidate can track state (the last known good value) while iterating and handle the edge case of leading `None` values.

---

### Break down the requirements

#### Step 1: Iterate through the list tracking the last non-None value

Maintain a variable for the most recent valid value.

#### Step 2: Replace None with the last known value

When encountering `None`, substitute the tracked value. If no valid value has been seen yet, leave it as `None`.

---

### The solution

**Single-pass forward fill**

```python
def forward_fill(values: list) -> list:
    result = []
    last_valid = None
    for val in values:
        if val is not None:
            last_valid = val
        result.append(last_valid)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) single pass.
> 
> **Space:** O(n) for the output list.

> **Interviewers Watch For**
>
> Whether you handle leading `None` values correctly. If the first values are `None`, there is nothing to fill forward from, so they remain `None`.

> **Common Pitfall**
>
> Filling leading `None` values with 0 instead of leaving them as `None`. The problem states that gaps before any real value should remain `None`.

---

## Common follow-up questions

- How would you implement backward fill instead? _(Tests iterating in reverse or using a second pass from right to left.)_
- What if you wanted to limit how many consecutive Nones can be filled? _(Tests adding a counter that resets on each non-None value.)_
- How does pandas `fillna(method='ffill')` work internally? _(Tests knowledge of the same algorithm applied to DataFrame columns.)_

## Related

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