Implement Array.flat

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Implement Array.flat

Approach

Use a recursive helper function that iterates over each item. If the item is an array and the remaining depth is greater than 0, recurse with depth - 1. Otherwise, push the item to the result. Concatenate sub-results to build the flattened output.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Recursive Flattening

Why It Works

The depth parameter controls how many levels of nesting to unwrap. Each recursive call decrements depth by 1, so arrays nested deeper than the specified depth are left as-is. Using Infinity flattens all levels.

Updated Feb 2026