Implement Stack using Queues (LeetCode 225): Solution and Explanation
Build a stack (last in, first out) out of a queue (first in, first out). Support push, pop, top and empty while only adding at the back of the queue and reading or removing at its front.
Intuition
A queue gives values back in arrival order, and a stack needs the reverse: the newest value first. So at some point the order inside the queue has to be flipped.
Flip it at push time. Right after adding x at the back, everything older than x sits in front of it. Take the front value and add it to the back, and repeat that once for each older value. Now x is at the front and the older values follow in the same newest-first order they already had.
Once the front of the queue is always the newest value, the other operations are trivial: pop removes the front, top reads it, and empty checks the size. You pay for the order once per push, and every read is O(1).
Approach: One queue, rotate after each push
- Keep a single queue whose front is always the top of the stack.
push(x): enqueuex, then repeatsize - 1times: dequeue the front and enqueue it at the back.pop(): dequeue and return the front.top(): return the front without removing it.empty(): return whether the queue has no values.
Step-by-step example
["MyStack","push","push","top","pop","empty"], [[],[1],[2],[],[],[]]
MyStack()creates an empty queue. Output so far:[null].push(1): the queue is empty, so 1 goes straight to the front. Queue[1].push(2): 2 joins at the back, giving[1, 2]. One rotation moves 1 from the front to the back:[2, 1]. The newest value is at the front.top()reads the front and returns 2.pop()dequeues the front and returns 2. Queue[1].empty()returns false because 1 is still stored. The output is[null,null,null,2,2,false].
Code: Python, Java, C++
1from collections import deque
2
3class MyStack:
4 def __init__(self):
5 self.q = deque()
6
7 def push(self, x: int) -> None:
8 self.q.append(x)
9 for _ in range(len(self.q) - 1):
10 self.q.append(self.q.popleft())
11
12 def pop(self) -> int:
13 return self.q.popleft()
14
15 def top(self) -> int:
16 return self.q[0]
17
18 def empty(self) -> bool:
19 return len(self.q) == 01class MyStack {
2 private Queue<Integer> q;
3
4 public MyStack() {
5 q = new LinkedList<>();
6 }
7
8 public void push(int x) {
9 q.offer(x);
10 for (int i = 0; i < q.size() - 1; i++) {
11 q.offer(q.poll());
12 }
13 }
14
15 public int pop() {
16 return q.poll();
17 }
18
19 public int top() {
20 return q.peek();
21 }
22
23 public boolean empty() {
24 return q.isEmpty();
25 }
26}1class MyStack {
2 queue<int> q;
3public:
4 MyStack() {
5 q = queue<int>();
6 }
7
8 void push(int x) {
9 q.push(x);
10 for (int i = 0; i + 1 < (int)q.size(); i++) {
11 q.push(q.front());
12 q.pop();
13 }
14 }
15
16 int pop() {
17 int x = q.front();
18 q.pop();
19 return x;
20 }
21
22 int top() {
23 return q.front();
24 }
25
26 bool empty() {
27 return q.empty();
28 }
29};Time and space complexity
O(n) push, O(1) pop/top/empty
A push into a queue of n values does n - 1 rotations. Pop, top and empty touch only the front or the size.
O(n)
The queue stores each value currently on the stack once.
Other approaches
Two queues, move on push (time O(n) push, O(1) pop, space O(n))
Enqueue x into an empty helper queue, move every value from the main queue behind it, then swap the two queues. It does the same O(n) work per push as the rotation, with an extra queue.
Two queues, move on pop (time O(1) push, O(n) pop/top, space O(n))
Push is a plain enqueue. For pop, move all but the last value into the helper queue, remove the last one, and swap. Pushes are O(1), but every pop and top costs O(n).
Common mistakes
- Rotating
sizetimes instead ofsize - 1. That walksxall the way around and leaves the queue in its original order. - Reading the size inside the loop condition after it changes. Rotation keeps the size constant, but compute the count before the loop if your language makes that unclear.
- Using stack-like operations on the underlying list, such as removing from the back. The problem only allows queue operations.
- In JavaScript,
Array.shiftis O(n), so a real queue (or an index pointer) is needed for large inputs.
Frequently asked questions
Why does rotating size - 1 times put the new value on top?
Before the rotation the new value is behind every older value. Each rotation moves one older value from in front of it to behind it. After all of them have moved, nothing is in front of the new value.
Can this be done with a single queue?
Yes. The rotation approach uses one queue. The two-queue versions are equivalent but use extra space for the helper queue.
Which operation should be expensive, push or pop?
Either works. Making push O(n) keeps pop and top O(1), which is better when reads are more frequent than writes.
What is the time complexity of Implement Stack using Queues?
With one queue and rotation on push, push is O(n) and pop, top and empty are O(1). Space is O(n).