Practice/Meta/Leetcode 2625. Flatten Deeply Nested Array
CodingMust
Given a multi-dimensional array (an array that may contain nested arrays of varying depths) and a non-negative integer representing a depth limit, create a function that flattens the array up to the specified depth.
When flattening, arrays at nesting levels less than the specified depth should have their elements extracted and placed into the parent array. Arrays that are nested at or beyond the depth limit should remain as nested arrays.
The depth is measured starting from 0 for top-level elements. For example, in [1, [2, 3]], the element 1 is at depth 0, while 2 and 3 are at depth 1 (inside one level of nesting).
0 <= depth <= 100Example 1:
Input: arr = [1, [2, 3], [4, [5]]], depth = 1 Output: [1, 2, 3, 4, [5]] Explanation: We flatten one level deep. The outer arrays [2, 3] and [4, [5]] are flattened, exposing 2, 3, 4, and [5]. The innermost array [5] stays nested because it's at depth 2.
Example 2:
Input: arr = [[1, 2, [3, 4]], [5, [6, [7]]]], depth = 2 Output: [1, 2, 3, 4, 5, 6, [7]] Explanation: Flattening 2 levels removes the first two layers of nesting. The deepest array [7] remains because it's at depth 3.
Example 3:
Input: arr = [1, [2, [3, [4]]]], depth = 0 Output: [1, [2, [3, [4]]]] Explanation: With depth 0, no flattening occurs. The array is unchanged.
Example 4:
Input: arr = [[[1]], [[2, 3]], [4, [5, [6]]]], depth = 3 Output: [1, 2, 3, 4, 5, 6] Explanation: All arrays are flattened completely since the maximum nesting depth doesn't exceed 3.