Skip to the solution
MediumDSA11 min read

How do you implement a queue using two stacks?

1.1k views

The problem

Question presented to candidate: "Implement a first-in, first-out queue in Python using only two stacks. Support push, pop, peek and empty, and tell me the time complexity of each operation."

What a strong answer should cover:

  • An inbox stack for pushes and an outbox stack for pops and peeks; pour inbox into outbox only when the outbox is empty.
  • Why pouring reverses the order so the oldest element is on top, and the invariant that pouring into a non-empty outbox would break.
  • Amortised O(1) per operation (each element moves at most once), worst case O(n) for a single pop.
  • The naive design that pours back after every pop is O(n) per pop.
  • Python specifics: lists as stacks with append/pop; in real code collections.deque is the queue to use, because list.pop(0) is O(n).

Clarifying questions expected:

  • "What should pop do on an empty queue: raise or return a sentinel?"
  • "Is amortised O(1) acceptable, or do you need a worst-case bound per call?"

Code / implementation expected: Yes โ€” a small Python class with two lists.

  • stack
  • queue

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

11 min read ยท 11 sections

Python code

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

PythonTwo-stack queue: trace every operation
PythonCounting element moves: lazy two-stack vs naive pour-back

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 48 of 154 in DSA

Keep your momentum going.

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

All DSA questions
Up nextMedium

How do you check if a binary tree is balanced?

Continue