The Gap Filler
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L4
- Asked in
- Meta
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.
Fill the Nones with the last real value.
Example 1
Input:
values = [1,null,2,3,null,null,5,null]
Output:
[1,1,2,3,3,3,5,5]
Example 2
Input:
values = [null,null,3,null]
Output:
[null,null,3,3]
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
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 resultCommon 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()`.)