The Depth of Field
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
- L3
- Asked in
- Citadel
Problem
A config export arrives as arbitrarily nested lists, but the consumer downstream only handles a fixed number of nesting levels. Collapse lst by exactly depth levels, preserving order, so a depth of 0 returns it untouched and anything still nested below the levels you collapse stays wrapped in its remaining sublists. A depth larger than the actual nesting simply flattens as far as the data goes.
Some containers hold containers that hold containers.
Example 1
Input:
lst = [[1,[2,[3]]]], depth = 1
Output:
[1,[2,[3]]]
Example 2
Input:
lst = [[1,[2,[3]]]], depth = 2
Output:
[1,2,[3]]
Worked solution and explanation
Why this problem exists in real interviews
Full flattening is the problem everyone has seen; the twist here is a brake. You are not collapsing everything, you are collapsing exactly depth levels and then stopping. The whole challenge lives in one decision: when you step into a sublist, do you remember that you just spent a level? Candidates who treat depth as a fixed constant instead of spending it on the way down either flatten everything or flatten nothing.
Break down the requirements
Step 1: Spend the budget, then stop
When you have no levels left to spend (depth is 0), every element is appended exactly as it is, even if it is itself a list. That is what keeps the deeper nesting intact.
Step 2: Descend only when you can afford it
For each element, only descend if it is a list AND you still have budget. Descend by recursing with depth decremented, so the brake is tracked separately on every branch of the nesting.
Step 3: Return the partially collapsed list
Elements nested deeper than the levels you collapsed come back wrapped in their remaining sublists, and the original left-to-right order is preserved throughout.
The solution
def flatten_to_depth(lst: list, depth: int) -> list:
result = []
for item in lst:
if isinstance(item, list) and depth > 0:
result.extend(flatten_to_depth(item, depth - 1))
else:
result.append(item)
return resultCommon 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, without recursion? (Tests using an explicit stack with per-element depth tracking.)
- What if `depth` is effectively infinite? (Tests falling back to full recursive flattening when there is no budget cap.)