🏷️ 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

ConceptWhy It Matters
RecursionHandle arbitrary depth
isinstance() checkType-aware iteration
extend vs appendList 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

Scroll to Top