Implement Queue using Stacks

EasyDesignLeetCode 232 ↗World 9-5
0:00 / 0:00

Build a first-in, first-out queue from two stacks: push onto one, and pour it into the other only when that runs dry. Each item moves once.

▼

The problem

LeetCode 232 (Easy). Implement a first-in, first-out queue (push, pop, peek, empty) using only two stacks (push to top, peek / pop from top, size, is empty).

Example (LeetCode's): ["MyQueue","push","push","peek","pop","empty"], [[],[1],[2],[],[],[]] → [null,null,null,1,1,false].

TRY IT ON LEETCODE ▶

The solution

class MyQueue:
    def __init__(self):
        self.in_stack, self.out_stack = [], []
    def push(self, x):
        self.in_stack.append(x)
    def peek(self):
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())
        return self.out_stack[-1]
    def pop(self):
        self.peek()
        return self.out_stack.pop()
    def empty(self):
        return not self.in_stack and not self.out_stack

Transcript

Implement Queue using Stacks. A queue is first in, first out, like a lunch line: the oldest tray is served first. Build one with push, pop, peek and empty, using only two stacks. A stack is last in, first out. You can only touch its top.

LeetCode's example: push one, then push two. Peek returns one, the oldest. Pop returns one too. Is it empty? No, two is still waiting, so false.

One stack alone hands out the newest tray first. The naive fix keeps the oldest tray on top. Every push moves all the trays to a helper stack, puts the new one at the bottom, and moves them back. The fifth push moves eight trays. That's order n per push.

The key idea: two stacks, In and Out. Push always drops onto In. Pop and peek always take from Out. When Out runs empty, pour every tray from In onto Out, one at a time. Pouring flips the pile, so the oldest tray lands on top.

In code, push is one append to In. Peek refills Out only when it's empty, then reads its top. Pop calls peek, then pops Out. Empty checks both stacks.

Let's run the example. Push one and two onto In. Peek: Out is empty, so pour two, then one. Now one is on top. Peek gives one, and pop serves one. Empty? Out still holds two, so false.

Keep going. Push three and four. They wait on In. Pop: Out isn't empty, so serve two, with no pouring. Pop again: Out is empty now, so pour four, then three, and serve three.

One pour can move many trays. Is that slow? No. Each tray is pushed once, poured once and popped once: three steps in its whole life. Spread out, that's amortized constant time per operation. The two stacks hold n trays: order n space.

Push onto In, pour when Out runs dry, serve from Out. That's Implement Queue using Stacks.