Implement Stack using Queues
Implement Stack using Queues is LeetCode 225 (Easy). Build MyStack, a last-in-first-out stack, using queues and only their standard operations (add to the back, peek or remove from the front, size, and is-empty):
push(x)putsxon top;pop()removes and returns the top element.top()returns the top element;empty()says whether the stack has no elements.
Every pop and top call is valid. The follow-up asks whether one queue is enough.
- 1 <= x <= 9
- At most 100 calls will be made to push, pop, top, and empty
- All the calls to pop and top are valid
Intuition
A queue only lets go of its oldest element, but a stack must give back its newest. A queue can still reorder itself without losing anything: take the front element off and add it at the back.
So after each push, cycle every older element behind the new one. The newest value is then at the front, where pop and top look, and the rest follow from newest to oldest. Every push restores that order, so reading the queue from front to back is the same as reading the stack from top to bottom.
"Build a LIFO structure from FIFO parts" with only front access means rotating: moving front elements to the back is the one way a queue can rearrange itself. Decide which call pays for the rotation, then keep the other calls trivial.
Approach
Before reading on, push 1, 2 and 3 into a single queue by hand. After each push, how many front-to-back moves put the newest value at the front?
Two ways to keep the newest value in front
Add the value at the back, then move the older elements from front to back.
- Answers the follow-up: one queue only.
- Less state: nothing to swap or keep in sync.
Put the value into an empty helper queue, move the main queue behind it, then swap the two.
- Easy to picture: the new value is first by construction.
- Extra container: same cost, more bookkeeping.
Both make push O(n) so that pop and top are O(1). The steps, code and live demo rotate one queue; the two-queue code follows the demo.
Add the new value at the back
push(x) first adds x to the back of the queue like any queue would. At that moment it is in the worst place for a stack, behind every older element, and the next step fixes that.
Rotate the older elements behind it
Repeat size − 1 times: remove the front element and add it at the back. Each older element passes behind x, and after the last move x is at the front with the others behind it, newest first.
Pop and top read the front
Because every push leaves the newest value at the front, pop() removes the front and top() returns it without removing it. Neither moves any other element.
Empty asks the queue
All elements live in the one queue, so empty() is just whether that queue is empty.
Code in Python, C++ and Java
size − 1 = 0 times.size − 1 = 0 times.Fill a second queue and swap
The textbook stack using two queues keeps everything in q1, newest first. To push, add the value to the empty q2, move every element of q1 behind it, then swap the names so q1 holds the new order and q2 is empty again. It moves the same elements as the rotation, through a second container.
Common pitfalls
Rotating size times instead of size − 1
for _ in range(len(self.q)):
self.q.append(self.q.popleft())for _ in range(len(self.q) - 1):
self.q.append(self.q.popleft())Moving every element, the new one included, brings the queue back to the order it had before the rotation, with the new value at the back again. Push 1, push 2, top returns 1 instead of 2.
Forgetting the swap in the two-queue version
self.q2.append(x)
while self.q1:
self.q2.append(self.q1.popleft())self.q2.append(x)
while self.q1:
self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1The reordered elements end up in q2, but pop and top read q1, which the loop just emptied. Push 1 then top fails on an empty queue.
Complexity
pop, top and empty touch only the front of the queue. The queue holds the n stored values and nothing else.Implement Stack using Queues FAQ
Can pop be the slow operation instead of push?
Yes. Let push just add to the back. Then pop moves all but the last element from front to back (or into a second queue) and removes the one left at the front. Push becomes O(1) and pop and top O(n), which suits a stack that is written far more often than it is read.
Is Python's deque allowed here?
Yes, as long as you use only its queue operations: append, popleft, q[0] and len. Calling q.pop() or q[-1] reads the back, which makes the deque a stack and skips the exercise.
Why does the queue built from stacks get amortized O(1) when this design does not?
Moving elements from stack to stack flips their order, so the work of one transfer is shared by many later reads. In Implement Queue using Stacks each element crosses once; a queue keeps order when it moves elements, so the rotation has to be redone on every push.