Problem Description
Given a multi-dimensional array arr and a depth n, return a version of the array that is flattened up to that depth. The first level (depth 0) elements should be flattened if they are arrays and if the current depth is less than n. Arrays at a depth equal to or above n should remain intact.
Key Insights
- Use recursion to traverse the array while tracking the current depth.
- Flatten an element (i.e. if it is an array) only when the current depth is less than n.
- If the current depth equals n, push the subarray as is.
- Ensure that both numbers and nested arrays are handled correctly and maintain order.
Space and Time Complexity
Time Complexity: O(total number of elements) – each element is processed once. Space Complexity: O(total number of elements) – additional space for the output array and recursion stack in the worst case.
Solution
The solution uses a recursive helper function that takes the current array and the current depth. For each element in the array, if it is not an array, it is added directly to the result. If it is an array and the current depth is less than n, the helper function is called recursively with depth incremented by 1 and the returned flattened elements are added to the result. Otherwise, if the element is an array and the current depth is n (or greater), it is simply appended without flattening. This algorithm ensures that arrays are flattened only up to the specified depth, preserving deeper nested arrays intact.