LeetCode #225 Easy

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) puts x on 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.

Constraints
  • 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
stackqueuedesign
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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?

1

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.

2

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.

3

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.

4

Empty asks the queue

All elements live in the one queue, so empty() is just whether that queue is empty.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3 
▶4class MyStack:
▶5 def __init__(self):
▶6 self.q = deque()
▶7 
▶8 def push(self, x: int) -> None:
▶9 self.q.append(x)
▶10 for _ in range(len(self.q) - 1):
▶11 self.q.append(self.q.popleft())
▶12 
▶13 def pop(self) -> int:
▶14 return self.q.popleft()
▶15 
▶16 def top(self) -> int:
▶17 return self.q[0]
▶18 
▶19 def empty(self) -> bool:
▶20 return not self.q
callqueuereturnedone empty queue: front on the left, back on the right
call
queue, front first[]
The stack lives in a single queue. The goal is to keep the newest value at the front, so that reading the queue front to back is the stack read top to bottom.
callpush 1queue1front, backreturnedadd 1 at the back: nothing older, done
callpush 1
queue, front first[1]
moves left0
1 is the only value, so it is already at the front. The rotation runs size − 1 = 0 times.
callpush 2queue12frontbackreturnedadd 2 at the back: 1 older to move
callpush 2
queue, front first[1, 2]
moves left1
2 joins at the back, behind 1 older value. A stack must return it first, so the 1 older value has to be moved behind it, one at a time.
callpush 2queue21frontback1returnedmove 1 from front to back: 2 is in front
callpush 2
queue, front first[2, 1]
moves left0
1 is taken off the front and added at the back, behind 2. Every older value is now behind 2, so 2 is at the front: the top of the stack.
calltopqueue21frontbackreturned2top: the front is 2 → return 2
calltop
queue, front first[2, 1]
The front holds the newest value, 2, so top returns it and leaves the queue as it is.
callpopqueue1front, backreturned22pop: remove 2 from the front → return 2
callpop
queue, front first[1]
2 is the newest value and sits at the front, so one removal from the front is the whole pop. 1 is now at the front, and it is the newest of the values left.
callemptyqueue1front, backreturned22falseempty: the queue holds 1 → false
callempty
queue, front first[1]
The queue still holds 1 value, so the stack is not empty: false.
callqueue1front, backreturned22falsereturned in order: 2, 2, false
returned[2, 2, false]
Each pop and top returned the newest value still stored, as a stack must. All the moving happened inside push, one front-to-back move per older value.
05

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.

▶1from collections import deque
▶2 
▶3 
▶4class MyStack:
▶5 def __init__(self):
▶6 self.q1 = deque()
▶7 self.q2 = deque()
▶8 
▶9 def push(self, x: int) -> None:
▶10 self.q2.append(x)
▶11 while self.q1:
▶12 self.q2.append(self.q1.popleft())
▶13 self.q1, self.q2 = self.q2, self.q1
▶14 
▶15 def pop(self) -> int:
▶16 return self.q1.popleft()
▶17 
▶18 def top(self) -> int:
▶19 return self.q1[0]
▶20 
▶21 def empty(self) -> bool:
▶22 return not self.q1
06

Common pitfalls

Rotating size times instead of size − 1

✗ Wrong
for _ in range(len(self.q)):
    self.q.append(self.q.popleft())
✓ Right
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

✗ Wrong
self.q2.append(x)
while self.q1:
    self.q2.append(self.q1.popleft())
✓ Right
self.q2.append(x)
while self.q1:
    self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1

The 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.

07

Complexity

Time
push O(n), pop and top O(1)
Space
O(n)
A push moves each of the other n − 1 elements once. pop, top and empty touch only the front of the queue. The queue holds the n stored values and nothing else.
08

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.