Explorer
JavaScript

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (use recursion to handle arbitrarily nested arrays).
  3. Implement Logic: Handle state and transformations efficiently (for each element, if it is an array, recursively flatten it).
  4. 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.

Deep Flatten Array

Medium

Write a function deepFlatten(arr) that completely flattens a deeply nested array.

Example Scenarios
1Example 1
Input: arr = [1, [2, [3, [4]], 5]]
Output: [1, 2, 3, 4, 5]
Explanation:

All nested levels recursively flattened.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[1,2,3,4,5,6,7]