Implement Queue using Stacks

Pattern: Queue using stacks

easy

Push onto an input stack. To read the front, pour the input stack into an output stack only when the output is empty: the order flips, so the oldest is on top. Each item moves at most once, so each operation is O(1) on average.

The problem

Build MyQueue with push(x), pop(), peek() and empty() using only stack operations. pop and peek are only called on a non-empty queue.

Think first

  • What happens to the order when one stack is poured into another?
  • When is it safe to pour?
  • How do you know the queue is empty?

Hints

    Brute force, and why it fails

    Pour everything across and back on every pop: O(n) per operation.

    The key insight

    Two stacks split the queue: the output holds the older part in the right order, the input collects new items. Pouring only when the output runs dry means each item crosses once.

    Dry run

    in1 2
    outempty

    push(1), push(2): in = [1, 2] (2 on top), out empty.

    Step 1 of 3

    The plan

    push(x): in.push(x)
    peek():  if out is empty: while in: out.push(in.pop())
             return out.top
    pop():   peek(); return out.pop()
    empty(): in is empty and out is empty
    

    Complexity

    Time
    O(1) amortised per operation
    Space
    O(n)

    Each item is pushed and popped at most twice over its whole life.

    Edge cases

    • Pushes after a pour: they wait in the input stack.
    • Alternating push and pop.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class MyQueue {
        private final Deque<Integer> in = new ArrayDeque<>(), out = new ArrayDeque<>();
    
        public void push(int x) {
            in.push(x);                             // new items go on the input stack
        }
    
        public int pop() {
            peek();                                 // make sure the output stack has the front on top
            return out.pop();
        }
    
        public int peek() {
            if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop());   // pour over only when out is empty
            return out.peek();
        }
    
        public boolean empty() {
            return in.isEmpty() && out.isEmpty();
        }
    }

    C++

    class MyQueue {
    public:
        stack<int> in, out;
    
        void push(int x) {
            in.push(x);                             // new items go on the input stack
        }
    
        int pop() {
            int x = peek();                         // make sure the output stack has the front on top
            out.pop();
            return x;
        }
    
        int peek() {
            if (out.empty()) while (!in.empty()) { out.push(in.top()); in.pop(); }   // pour over only when out is empty
            return out.top();
        }
    
        bool empty() {
            return in.empty() && out.empty();
        }
    };

    Python

    class MyQueue:
        def __init__(self):
            self.inp, self.out = [], []
    
        def push(self, x: int) -> None:
            self.inp.append(x)                      # new items go on the input stack
    
        def pop(self) -> int:
            self.peek()                             # make sure the output stack has the front on top
            return self.out.pop()
    
        def peek(self) -> int:
            if not self.out:
                while self.inp:                     # pour over only when out is empty
                    self.out.append(self.inp.pop())
            return self.out[-1]
    
        def empty(self) -> bool:
            return not self.inp and not self.out

    Common mistakes

    • Pouring while the output is not empty.
    • Checking only one stack in empty().

    Similar problems