|
| 1 | +2625\. Flatten Deeply Nested Array |
| 2 | + |
| 3 | +Medium |
| 4 | + |
| 5 | +Given a **multi-dimensional** array `arr` and a depth `n`, return a **flattened** version of that array. |
| 6 | + |
| 7 | +A **multi-dimensional** array is a recursive data structure that contains integers or other **multi-dimensional** arrays. |
| 8 | + |
| 9 | +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`. |
| 10 | + |
| 11 | +Please solve it without the built-in `Array.flat` method. |
| 12 | + |
| 13 | +**Example 1:** |
| 14 | + |
| 15 | +**Input** arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 0 |
| 16 | + |
| 17 | +**Output:** [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] |
| 18 | + |
| 19 | +**Explanation:** Passing a depth of n=0 will always result in the original array. This is because the smallest possible depth of a subarray (0) is not less than n=0. Thus, no subarray should be flattened. |
| 20 | + |
| 21 | +**Example 2:** |
| 22 | + |
| 23 | +**Input** arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 1 |
| 24 | + |
| 25 | +**Output:** [1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15] |
| 26 | + |
| 27 | +**Explanation:** The subarrays starting with 4, 7, and 13 are all flattened. This is because their depth of 0 is less than 1. However [9, 10, 11] remains unflattened because its depth is 1. |
| 28 | + |
| 29 | +**Example 3:** |
| 30 | + |
| 31 | +**Input** arr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 2 |
| 32 | + |
| 33 | +**Output:** [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] |
| 34 | + |
| 35 | +**Explanation:** The maximum depth of any subarray is 1. Thus, all of them are flattened. |
| 36 | + |
| 37 | +**Constraints:** |
| 38 | + |
| 39 | +* <code>0 <= count of numbers in arr <= 10<sup>5</sup></code> |
| 40 | +* <code>0 <= count of subarrays in arr <= 10<sup>5</sup></code> |
| 41 | +* `maxDepth <= 1000` |
| 42 | +* `-1000 <= each number <= 1000` |
| 43 | +* `0 <= n <= 1000` |
0 commit comments