# The Gap Filler

> Fill the Nones with the last real value.

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

Domain: Python · Difficulty: easy · Seniority: L4

## 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 None appears before any non-None value, leave it as None.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **forward fill**, one of the most common time-series imputation techniques. It probes single-pass state tracking and correct handling of edge cases at the boundaries.

---

### Break down the requirements

#### Step 1: Track the last non-None value

Initialize to `None`. Update whenever a non-None value is encountered.

#### Step 2: Replace None with the tracked value

If the tracked value is still `None` (no prior non-None seen), the gap stays `None`.

---

### The solution

**Forward fill with last-known-value tracking**

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

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

> **Interviewers Watch For**
>
> Whether you use `is not None` instead of truthiness checks. A value of `0` is valid data but falsy, so `if val` would incorrectly skip it.

> **Common Pitfall**
>
> Using `if val` instead of `if val is not None`. This treats `0` and `''` as gaps when they are legitimate values.

---

## Common follow-up questions

- How would you implement backward fill? _(Tests iterating in reverse or making a second pass.)_
- What if you wanted linear interpolation instead? _(Tests finding the next non-None value and computing intermediate values.)_
- How does this work in pandas? _(Tests `Series.fillna(method='ffill')` or `Series.ffill()`.)_

## Related

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