Flatten Deeply Nested Array - Problem

Given a multi-dimensional array arr and a depth n, return a flattened version of that array.

A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.

A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array are considered to be 0.

Note: Please solve it without the built-in Array.flat method.

Input & Output

Example 1 — Basic Nested Array
$ Input: arr = [1, 2, [3, 4, [5, 6]]], n = 1
Output: [1, 2, 3, 4, [5, 6]]
💡 Note: Flatten one level deep: the outer [3, 4, [5, 6]] becomes 3, 4, [5, 6], but [5, 6] stays nested since we only flatten 1 level
Example 2 — Deep Flattening
$ Input: arr = [1, [2, [3, [4]]]], n = 3
Output: [1, 2, 3, 4]
💡 Note: Flatten 3 levels deep: all nested arrays are flattened since the maximum nesting depth is 3
Example 3 — No Flattening
$ Input: arr = [[1, 2, 3], [4, 5, 6]], n = 0
Output: [[1, 2, 3], [4, 5, 6]]
💡 Note: No flattening when n = 0: the array remains unchanged

Constraints

  • 0 ≤ arr.length ≤ 105
  • 0 ≤ n ≤ 1000
  • Array can contain integers or other arrays
  • -103 ≤ arr[i] ≤ 103 for integer elements

Visualization

Tap to expand
Flatten Deeply Nested Array with Depth ControlInput:arr = [1, [2, 3], [4, [5]], 6]n = 1 (flatten only 1 level deep)Process:Depth 0 → Depth 1:• 1 stays 1• [2, 3] → 2, 3• [4, [5]] → 4, [5] (stop at depth 1)Depth Control:• [5] remains nested• Only flatten when current_depth < nOutput:result = [1, 2, 3, 4, [5], 6]
Understanding the Visualization
1
Input
Multi-dimensional array [1, [2, 3], [4, [5]]] and depth n=1
2
Process
Flatten arrays only when current depth < n
3
Output
Partially flattened array [1, 2, 3, 4, [5]]
Key Takeaway
🎯 Key Insight: Control flattening depth by tracking current nesting level and only flattening when depth < n
Asked in
Google 23 Meta 18 Microsoft 15 Amazon 12
34.5K Views
Medium Frequency
~15 min Avg. Time
892 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