π·οΈΒ Category:Β Lists / Recursion Β |Β π―Β Difficulty:Β MediumΒ Β |Β π₯Β Frequency:Β β
β
β
β
β
π Problem Statement
Given a nested list of integers (any depth), return a flat list with all integers. This process is essential to Flatten a Nested List.
π₯ Input β [1, [2, [3, 4]], [5, 6]]
π€ Output β [1, 2, 3, 4, 5, 6]
π₯ Input β [[1, 2], [3, [4, [5]]]]
π€ Output β [1, 2, 3, 4, 5]
π₯ Input β [1, 2, 3]
π€ Output β [1, 2, 3]
π§ What the Interviewer is Testing
| Concept | Why It Matters |
|---|---|
| Recursion | Handle arbitrary depth |
| isinstance() check | Type-aware iteration |
| extend vs append | List building |
π‘ Approach
For each item in the list:
β If item is a list β recurse into it (flatten it too)
β If item is a value β append directly to result
β Optimal Solution β Recursive
def flatten(nested: list) -> list:
result = []
for item in nested:
if isinstance(item, list):
result.extend(flatten(item)) # recurse
else:
result.append(item) # base value
return result
# ββ Test Cases βββββββββββββββββββββββββββββββββ
print(flatten([1, [2, [3, 4]], [5, 6]])) # β
[1, 2, 3, 4, 5, 6]
print(flatten([[1, 2], [3, [4, [5]]]])) # β
[1, 2, 3, 4, 5]
print(flatten([1, 2, 3])) # β
[1, 2, 3]
print(flatten([])) # β
[]
π Iterative Alternative (using a stack)
def flatten_iterative(nested: list) -> list:
stack = nested[::-1] # reverse so we pop from front
result = []
while stack:
item = stack.pop()
if isinstance(item, list):
stack.extend(item[::-1])
else:
result.append(item)
return result
π Complexity Analysis
βββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββ
β Time O(n) β n = total number of elements at all levels β
β Space O(d) β d = depth of nesting (recursion stack) β
βββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββ
π€ How to Explain in the Interview
βIβll use recursion. For each item, if itβs a list I recursively flatten it and extend my result. If itβs a value I append directly. This handles arbitrary depth nesting in O(n) time where n is the total number of elements.β
βIβll use recursion. For each item, if itβs a list I recursively flatten it and extend my result. If itβs a value I append directly. This handles arbitrary depth nesting in O(n) time where n is the total number of elements.β
π Common Follow-up Questions
Q1 β Flatten only one level deep?
import itertools
def flatten_one_level(nested):
return list(itertools.chain.from_iterable(nested))
Q2 β Using a generator?
def flatten_gen(nested):
for item in nested:
if isinstance(item, list):
yield from flatten_gen(item)
else:
yield item
# Memory efficient for large structures
π Set 1 of 4 β Python Interview Prep Series β devprepguide.com
