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 Iterative with Stack Approach INPUT Nested Array Structure 1 2 [3,4,[5,6]] 3 4 [5,6] 5 6 Depth 0 Depth 1 Depth 2 Input Values: arr = [1,2,[3,4,[5,6]]] n = 1 (flatten depth) ALGORITHM STEPS 1 Initialize Stack Push [arr, depth=0] pairs Stack: [[arr, 0]] Result: [] Process right-to-left 2 Pop and Check Is item array? Check depth If array AND depth < n: Expand: push children with depth+1 3 Add to Result If not array OR depth >= n result.push(item) as-is [5,6] stays nested (depth=1) 4 Repeat Until Empty Stack empty? Return result Iterations for this example: 1-->2-->3-->4-->[5,6] FINAL RESULT Flattened (1 level deep) 1 2 3 4 [5,6] Blue: Original level 0 Green: Flattened from level 1 Orange: Kept nested (n=1 limit) Before vs After: IN: [1,2,[3,4,[5,6]]] OUT: [1,2,3,4,[5,6]] Level 1 flattened, level 2 kept Output: [1, 2, 3, 4, [5, 6]] OK - Correctly flattened! Key Insight: The stack-based approach processes elements with their depth tracking. When we encounter an array and current depth < n, we expand it by pushing its elements with depth+1. Otherwise, we keep the element as-is. This allows controlled flattening to exactly n levels without recursion! TutorialsPoint - Flatten Deeply Nested Array | Iterative with Stack
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