Flatten an Array Without Recursion

ArraysStackInterview Question

Write flattenIterative(arr) returning every value from a deeply nested array in order.

The function must not call itself. This is the follow-up an interviewer asks once you have written the recursive version, and the point is the depth limit: recursion runs out of stack, an explicit stack runs out of memory.

Examples

Example 1
Input
flattenIterative([1, [2, [3, [4]]], 5]);
Output
[1, 2, 3, 4, 5]
Explanation
Order is preserved, however deep the nesting goes.

Constraints

  • Nesting may be tens of thousands deep
  • Values are numbers

Notes

  • Popping from the end visits items in reverse, so the result needs reversing — or push in the other order.

Hints

Read the full write-up for Flatten an Array Without Recursion
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it