Flatten Deeply Nested Array - Problem
Flatten a Multi-Dimensional Array with Depth Control

Imagine you have a nested Russian doll of arrays - arrays inside arrays inside arrays! Your task is to flatten this multi-dimensional structure, but with a twist: you can only unwrap up to a certain depth n.

Given a multi-dimensional array arr and a depth limit n, return a flattened version where:
• Sub-arrays are removed and replaced with their actual elements
• Flattening only occurs if the current nesting depth is less than n
• Elements at depth 0 are the outermost array elements

Challenge: Solve this without using the built-in Array.flat()

Example: [1, [2, [3, 4]], 5] with depth 1 becomes [1, 2, [3, 4], 5]

Input & Output

example_1.py — Basic Flattening
$ Input: arr = [1, [2, [3, 4]], 5], n = 1
Output: [1, 2, [3, 4], 5]
💡 Note: With depth 1, we flatten the first level of nesting. The outer array contains [2, [3, 4]] which gets flattened to 2 and [3, 4], but [3, 4] remains nested since we've reached our depth limit.
example_2.py — Deeper Flattening
$ Input: arr = [1, [2, [3, 4]], 5], n = 2
Output: [1, 2, 3, 4, 5]
💡 Note: With depth 2, we can flatten two levels deep. This completely flattens the array since the deepest nesting is only 2 levels deep.
example_3.py — No Flattening
$ Input: arr = [[1, 2], [3, 4]], n = 0
Output: [[1, 2], [3, 4]]
💡 Note: With depth 0, no flattening occurs. The array remains exactly as provided since we're not allowed to flatten any levels.

Constraints

  • 0 ≤ n ≤ 1000
  • Array can contain integers and nested arrays
  • Maximum nesting depth ≤ 1000
  • No built-in Array.flat() method allowed
  • Array length can be from 0 to 104 elements

Visualization

Tap to expand
Depth-Controlled Array FlatteningOuter Doll[1,[2,[3,4]],5]Depth 0n=2Middle Doll[2,[3,4]]Depth 1Inner Doll[3,4]Depth 2UNPACKdepth < nUNPACKdepth < nFinal Result12[3,4]5← Preserved (depth = n)
Understanding the Visualization
1
Start with Outer Shell
Begin with the outermost array container at depth 0
2
Check Depth Limit
For each nested array, verify if we can go deeper (depth < n)
3
Recursively Unpack
If within limit, recursively process sub-arrays with decremented depth
4
Preserve Deep Nesting
Arrays beyond depth limit remain intact in the final result
Key Takeaway
🎯 Key Insight: Recursion with depth tracking provides elegant control over flattening levels, allowing us to preserve nested structure beyond our specified limit while efficiently processing all accessible elements.
Asked in
Google 42 Meta 38 Amazon 35 Microsoft 28
41.3K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen