Skip to the solution
HardDSAAsked in 20245 min read

Queue via two stacks

2.8k views

The problem

Problem, as an interviewer would state it: "Implement a FIFO queue using only two stacks (LIFO structures). Discuss edge cases, runtime, and alternatives."

Examples:

Code
q.enqueue(1); q.enqueue(2); q.enqueue(3);
q.dequeue(); // 1
q.dequeue(); // 2
q.enqueue(4);
q.dequeue(); // 3

Clarifying questions expected:

  • Which operations are needed: enqueue, dequeue, peek, size, isEmpty?
  • What should dequeue and peek return on an empty queue?
  • What runtime is expected: is amortized O(1) per operation acceptable?

Code / implementation expected: Yes — real, direct proof against a reference queue, a measurement of the amortized cost, and the classic bug.

  • js-coding
  • utility
  • 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

5 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: a two-stack queue matches an array queue on random operations, moves each element at most once, and avoids the shift() slowdown on large queues

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 133 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

Virtual DOM diff algorithm

Continue