Write a function `flattenOnce(arr)` that flattens a nested array by one level.
Problem Statement
<p>Write a function <code>flattenOnce(arr)</code> that flattens a nested array by one level.</p>
Examples
Input: arr = [1, [2, 3], [4, [5]]]
Output: [1, 2, 3, 4, [5]]
Explanation: Flattened exactly one level deep.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Array.concat() can merge arrays together.
š” Hint 2:
The spread operator can be used with concat to flatten one level.
š” Hint 3:
return [].concat(...arr); or arr.flat(1);
Editorial & Approach
Problem Overview & Intuition
To solve Flatten Nested Array (One Level), we consider the execution characteristics of JavaScript engines. Write a function `flattenOnce(arr)` that flattens a nested array by one level. 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 (array.concat() can merge arrays together).
- Implement Logic: Handle state and transformations efficiently (the spread operator can be used with concat to flatten one level).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function flattenOnce(arr) {
return [].concat(...arr);
}
Complexity Analysis
Time Complexity
O(N) linear scan over input
Space Complexity
O(1) constant auxiliary space (or O(N) output)
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.