Write a function `deepFlatten(arr)` that completely flattens a deeply nested array.
Problem Statement
<p>Write a function <code>deepFlatten(arr)</code> that completely flattens a deeply nested array.</p>
Examples
Input: arr = [1, [2, [3, [4]], 5]]
Output: [1, 2, 3, 4, 5]
Explanation: All nested levels recursively flattened.
Complexity
Time Complexity: O(N)
Space Complexity: O(D)
Hints
š” Hint 1:
Use recursion to handle arbitrarily nested arrays.
š” Hint 2:
For each element, if it is an array, recursively flatten it.
š” Hint 3:
return arr.reduce((flat, item) => flat.concat(Array.isArray(item) ? deepFlatten(item) : item), []);
Editorial & Approach
Problem Overview & Intuition
To solve Deep Flatten Array, we consider the execution characteristics of JavaScript engines. Write a function `deepFlatten(arr)` that completely flattens a deeply nested array. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use recursion to handle arbitrarily nested arrays).
- Implement Logic: Handle state and transformations efficiently (for each element, if it is an array, recursively flatten it).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function deepFlatten(arr) {
return arr.reduce((flat, item) => {
return flat.concat(Array.isArray(item) ? deepFlatten(item) : item);
}, []);
}
Complexity Analysis
Time Complexity
O(N) where N is total nested elements
Space Complexity
O(D) call stack depth
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.