Skip to the solution
HardDSAAsked in 20246 min read

Flatten a Deeply Nested Array Iteratively (No Recursion, No Call-Stack Limit)

2.7k views

The problem

Problem, as an interviewer would state it: "Implement a function to flatten a nested array completely, iteratively (no recursion) using a stack. It must correctly handle sparse-array holes and circular references."

Examples:

Code
flatten([1, [2, [3, [4, [5]]]], 6]); // [1, 2, 3, 4, 5, 6]
flatten([1, , [2, , [, 3]], , 4]);   // [1, 2, 3, 4]   (holes are skipped)

Clarifying questions expected:

  • What should a circular reference do — throw, skip, or stop early?
  • Should an array that is merely shared (referenced twice, but not inside itself) be flattened each time?
  • Should there be a depth limit, matching Array.prototype.flat(depth)?

Code / implementation expected: Yes — real, direct proof against native flat, at depths where recursion (and native flat) fail.

  • array
  • stack
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: an explicit-stack flatten matches native flat, skips holes, distinguishes cycles from shared arrays, and survives depths where native flat throws

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 135 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Create lazy evaluator

Continue