# Extract Leaf Values

> The tree has leaves. Pluck them.

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

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Given a nested dict (leaves are any non-dict values), return a flat list of leaves in depth-first traversal order of the keys. Within a dict level, iterate keys in insertion order.

## Worked solution and explanation

### Why this problem exists in real interviews

Extracting leaf values from a nested dict tests **recursive traversal** of tree-like structures. It checks whether you can distinguish container nodes (dicts) from leaf values and collect results in traversal order.

---

### Break down the requirements

#### Step 1: Iterate over dict values

For each value in the dictionary, determine if it is itself a dict (continue recursing) or a leaf (collect it).

#### Step 2: Recurse into nested dicts

If a value is a dict, recursively extract its leaf values and append them to the result.

#### Step 3: Collect non-dict values as leaves

Any value that is not a dict is a leaf and should be added to the result list.

---

### The solution

**Recursive dict traversal collecting non-dict values**

```python
def leaf_values(d):
    result = []
    for key in d:
        value = d[key]
        if isinstance(value, dict):
            leaves = leaf_values(value)
            for leaf in leaves:
                result.append(leaf)
        else:
            result.append(value)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the total number of values (both leaf and intermediate) in the nested structure.
> 
> **Space:** O(n + d) where d is the max nesting depth for the recursion stack and n is the total number of leaf values.

> **Interviewers Watch For**
>
> Using `isinstance(value, dict)` as the branching condition. This clearly separates container traversal from leaf collection.

> **Common Pitfall**
>
> Iterating over `d.items()` but then only using the value. While not wrong, it is cleaner to iterate `d.values()` if you do not need the key. However, iterating `d` (keys) and indexing is also fine.

---

## Common follow-up questions

- What if lists inside the dict should also be recursed into? _(Tests extending the isinstance check to handle both dict and list containers.)_
- How would you return key paths alongside leaf values? _(Tests tracking the path as a list of keys during recursion.)_
- What if the nesting depth is extreme (e.g., 10,000 levels)? _(Tests iterative approach using an explicit stack to avoid recursion limit issues.)_

## Related

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