Implement Stack using Queues

Easystackdesignqueue
Category: System Design
Companies that ask this question:
AmazonMicrosoftBloomberg

Approach

Implement Stack using Queues

Approach

Use single queue with rotation to maintain LIFO order.

Algorithm

  1. Push: Add element then rotate queue n-1 times
    • Makes newest element at front
  2. Pop: Remove from front (newest element)
  3. Top: Peek at front
  4. Empty: Check if queue empty

Complexity

  • Time: O(n) push, O(1) pop/top/empty
  • Space: O(n) - queue storage

Key Insights

  • Rotation maintains stack order in queue
  • Alternative: Use two queues for O(1) push

Solution

java
1class MyStack {
2    private Queue<Integer> queue;
3    
4    public MyStack() {
5        queue = new LinkedList<>();
6    }
7    
8    public void push(int x) {
9        queue.offer(x);
10        int size = queue.size();
11        for (int i = 1; i < size; i++) {
12            queue.offer(queue.poll());
13        }
14    }
15    
16    public int pop() {
17        return queue.poll();
18    }
19    
20    public int top() {
21        return queue.peek();
22    }
23    
24    public boolean empty() {
25        return queue.isEmpty();
26    }
27}
Loading visualizer...