Flatten Nested List

Medium~15 min

Given a nested list of integers (which can contain integers or other nested lists), flatten it into a single list of integers using recursion.

The nesting can be arbitrarily deep. Your solution must handle any level of nesting.

For example, [1, [2, [3, 4], 5], 6] should become [1, 2, 3, 4, 5, 6].

You must solve this problem recursively — do not use any built-in flatten methods.

Examples

Example 1
Input: nested = [1, [2, [3, 4], 5], 6]
Output: [1, 2, 3, 4, 5, 6]
Explanation: The nested structure is flattened by recursively extracting all integers in order.
Example 2
Input: nested = [[1, 2], [3, [4, 5]]]
Output: [1, 2, 3, 4, 5]
Explanation: Two top-level lists, one of which contains a further nested list.
Example 3
Input: nested = [1, 2, 3]
Output: [1, 2, 3]
Explanation: Already flat — no nested lists to unpack.

Constraints

  • The list can be nested to any depth
  • All leaf values are integers in the range -10^4 to 10^4
  • Total number of integers <= 10^4
  • You must use recursion (no built-in flatten methods)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run