Skip to content
UniCircle
EasyCodingArrays

Flatten a deeply nested array

Question JS-COD-001

A JSON array may contain integers and other arrays, nested to any depth. Print a single flat array that contains every integer in the order it appears when you read the input from left to right.

Do not use Array.prototype.flat(Infinity) — write the flattening yourself. (Interviewers ask this to see recursion or an explicit stack.)

Constraints

  • The input is at most 20000 characters.
  • Nesting depth is at most 50.
  • Every leaf value is an integer between −10^6 and 10^6.

Input and output

Input
One line: a JSON array.
Output
One line: the flat array as compact JSON (no spaces), for example `[1,2,3]`.

Examples

Input 1

[1,[2,[3,4]],5]

Output

[1,2,3,4,5]

Every number, left to right, regardless of depth.

Input 2

[[10],[],[[20,[30]]]]

Output

[10,20,30]

Empty arrays contribute nothing.

Show hints
  • If an item is an array, flatten it the same way; otherwise keep it.
  • An explicit stack avoids recursion depth limits.
Show the explanation

Walk the structure depth-first. The recursive version is short: for each item, if it is an array, append the flattening of that item; otherwise append the item.

An iterative version avoids deep recursion: push the input onto a stack of iterators, take the next item from the top iterator, descend into arrays, and pop an iterator when it is exhausted. Each number and each array is visited once, so the work is linear in the size of the input.

Printing uses JSON.stringify, which produces compact JSON by default.

Original UniCircle question. Last reviewed 22 Oct 2026.