Implement Stack using Queues

Pattern: Queue using stacks

easy

Use one queue. After adding x, move each older item from the front to the back, size - 1 times, so x ends at the front. Then pop and top just use the front.

The problem

Build MyStack with push(x), pop(), top() and empty() using only queue operations: add at the back, remove and read at the front, size and empty. pop and top are only called on a non-empty stack.

Think first

  • Which item must a stack return next?
  • Where does a queue let you read?
  • How can you move the newest item to the front?

Hints

    Brute force, and why it fails

    Two queues: on pop, move all but the last item to the other queue: O(n) per pop.

    The key insight

    Rotating on every push keeps the queue in stack order, newest first, so reads are O(1).

    Dry run

    10 

    push(1): queue [1].

    Step 1 of 3

    The plan

    push(x): q.add(x)
             repeat q.size - 1 times: q.add(q.remove())
    pop():   return q.remove()
    top():   return q.front
    

    Complexity

    Time
    O(n) push, O(1) others
    Space
    O(n)

    Each push moves every older item once.

    Edge cases

    • One item: no rotation.
    • Pop until empty, then push again.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class MyStack {
        private final Queue<Integer> q = new ArrayDeque<>();
    
        public void push(int x) {
            q.add(x);
            for (int i = 1; i < q.size(); i++) q.add(q.poll());   // rotate the older items behind x, so x is at the front
        }
    
        public int pop() {
            return q.poll();
        }
    
        public int top() {
            return q.peek();
        }
    
        public boolean empty() {
            return q.isEmpty();
        }
    }

    C++

    class MyStack {
    public:
        queue<int> q;
    
        void push(int x) {
            q.push(x);
            for (size_t i = 1; i < q.size(); i++) { q.push(q.front()); q.pop(); }   // rotate older items behind x
        }
    
        int pop() {
            int x = q.front();
            q.pop();
            return x;
        }
    
        int top() {
            return q.front();
        }
    
        bool empty() {
            return q.empty();
        }
    };

    Python

    from collections import deque
    
    
    class MyStack:
        def __init__(self):
            self.q = deque()
    
        def push(self, x: int) -> None:
            self.q.append(x)
            for _ in range(len(self.q) - 1):        # rotate the older items behind x, so x is at the front
                self.q.append(self.q.popleft())
    
        def pop(self) -> int:
            return self.q.popleft()
    
        def top(self) -> int:
            return self.q[0]
    
        def empty(self) -> bool:
            return not self.q

    Common mistakes

    • Rotating size times, which puts x back at the end.
    • Using a deque's back end, which is not a queue operation.

    Similar problems