#2625
Flatten Deeply Nested Array
MediumRecursionDepth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses recursion to flatten the array while keeping track of the current depth. This allows us to only flatten elements when the current depth is less than n, making the solution efficient and straightforward.
⚙️
Algorithm
6 steps- 1Step 1: Define a recursive function that takes the current array and depth.
- 2Step 2: Initialize an empty result array.
- 3Step 3: Iterate through each element in the array.
- 4Step 4: If the element is an integer, add it to the result array.
- 5Step 5: If the element is an array and the current depth is less than n, recursively flatten it and add to the result.
- 6Step 6: If the element is an array and the current depth is equal to or greater than n, add it as is to the result.
solution.py11 lines
1def flatten(arr, n, depth=0):
2 result = []
3 for element in arr:
4 if isinstance(element, list):
5 if depth < n:
6 result.extend(flatten(element, n, depth + 1))
7 else:
8 result.append(element)
9 else:
10 result.append(element)
11 return resultℹ
Complexity note: The time complexity is O(n) because we visit each element in the array exactly once. The space complexity is O(n) due to the space used for the result array.
- 1Understanding recursion is crucial for solving nested structures.
- 2Keeping track of depth allows for controlled flattening.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.