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
.
Please solve it without the built-in Array.flat
method.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
0 <= count of numbers in arr <= 10^5
0 <= count of subarrays in arr <= 10^5
maxDepth <= 1000
-1000 <= each number <= 1000
0 <= n <= 1000
Solution
Method 1 – Recursive Depth-Limited Flattening
Intuition
The key idea is to recursively traverse the array, flattening subarrays only if their current depth is less than the given limit n
. This ensures that subarrays at or above the depth limit remain nested.
Approach
- Define a helper function that takes the current array and its depth.
- For each element in the array:
- If it is an integer, add it to the result.
- If it is an array and the current depth is less than
n
, recursively flatten it with depth + 1 and add its elements to the result. - If it is an array and the current depth is
n
or more, add the subarray as is.
- Return the result array.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m)
wherem
is the total number of elements (including all nested elements), since each element is visited once. - 🧺 Space complexity:
O(m)
due to recursion stack and the result array.