Queue using Stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue: push, peek, pop, and empty. void push(int x) pushes element x to the back. int pop() removes and returns the front element. int peek() returns the front element. boolean empty() returns true if empty. Each operation must only use standard stack operations.
- 1 <= x <= 9
- At most 100 calls to push, pop, peek, and empty
- All calls to pop and peek are valid (queue will not be empty)
push(1), push(2), peek(), pop(), empty()1, 1, falsepush(1), pop(), push(2), peek()1, 2A stack is like a tube where you only ever touch the top (LIFO). A queue is like a tunnel where people enter one end and exit the other (FIFO). One stack is backwards for a queue, but two stacks together can fix this!
Think of it as a Waterfall. You pour items from one container into another, and the order flips perfectly. By doing this pour only when our exit container is empty, we convert LIFO into FIFO with very little extra work.
We maintain two stacks: an inStack for arrivals and an outStack for departures.
- Push: Always add the new person to the back of the arrival line (inStack).
- Pop/Peek: We need the person at the very front. If our departure stack (outStack) is empty, we pour everything from the arrival stack into it. Because of the LIFO property, the person who was at the very bottom of the arrival stack (the first one to arrive) is now at the very top of the departure stack!
- Amortized Efficiency: Even though a single transfer might take time, every item only moves from one stack to the other exactly once. This means the overall cost is constant over time.
CLASS MyQueue:
inStack = []
outStack = []
FUNCTION push(x):
inStack.PUSH(x)
FUNCTION pop():
transfer_if_needed()
RETURN outStack.POP()
FUNCTION peek():
transfer_if_needed()
RETURN outStack.PEEK()
FUNCTION transfer_if_needed():
IF outStack is empty:
WHILE inStack is NOT empty:
outStack.PUSH(inStack.POP())Bridging LIFO and FIFO with Dual Stacks
The Reversal Insight
A single stack reverses order (LIFO). By transferring to a second stack, we reverse the reversal, effectively yielding the original order (FIFO).
Strategy: Lazy Transfer
Don't move elements unnecessarily. Only transfer from Inbox (S1) to Outbox (S2) when S2 is empty and a Pop/Peek is requested.