# The Depth of Field

> Some containers hold containers that hold containers.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a nested list and a non-negative integer depth, flatten the list by `depth` levels. depth=0 returns the list unchanged. depth=1 flattens one level. Anything nested deeper than the depth remains as a sublist.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **depth-controlled recursive flattening**, a more precise version of full list flattening. It probes whether a candidate can manage a depth parameter to stop recursion at the right level.

---

### Break down the requirements

#### Step 1: Check the depth parameter

If depth is 0, return the input as-is (do not flatten further).

#### Step 2: Iterate and conditionally recurse

For each element, if it is a list and depth is greater than 0, recurse with depth decremented. Otherwise, append it directly.

#### Step 3: Return the partially flattened list

Elements deeper than the specified depth remain as nested sublists.

---

### The solution

**Depth-limited recursive flattening**

```python
def flatten(nested: list, depth: int) -> list:
    result = []
    for item in nested:
        if isinstance(item, list) and depth > 0:
            sub = flatten(item, depth - 1)
            for val in sub:
                result.append(val)
        else:
            result.append(item)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the total number of elements at all levels up to the specified depth.
> 
> **Space:** O(n + d) where d is the recursion depth (capped by the depth parameter).

> **Interviewers Watch For**
>
> Whether the depth parameter correctly controls recursion. `depth=0` should return the original list unchanged.

> **Common Pitfall**
>
> Off-by-one on depth: `depth=1` should flatten one level of nesting, meaning top-level sublists are expanded but their sublists are not.

---

## Common follow-up questions

- What does JavaScript's `Array.flat(depth)` do differently? _(Tests cross-language awareness of the same concept.)_
- How would you implement this iteratively? _(Tests using a stack with depth tracking per element.)_
- What if depth is infinity? _(Tests falling back to full recursive flattening.)_

## Related

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