Implement a FIFO (First-In-First-Out) queue using only two stacks with standard stack operations (push, top, pop, empty).
Approach: Use an input stack for push and an output stack for pop. Transfer elements when output stack is empty.
Imagine: Two Boxes of Plates
- Input box: Stack new plates on top
- Output box: When empty, flip all plates from input box
- This reverses the order twice β original order preserved
Example: push(1), push(2), pop(), push(3), pop()
- push(1): input=[1], output=[]
- push(2): input=[1,2], output=[]
- pop(): output empty β transfer β input=[], output=[2,1] β pop returns 1
- push(3): input=[3], output=[2]
- pop(): output not empty β returns 2
class MyQueue:
def __init__(self):
self.input = []
self.output = []
def push(self, x):
self.input.append(x)
def pop(self):
self.peek()
return self.output.pop()
def peek(self):
if not self.output:
while self.input:
self.output.append(self.input.pop())
return self.output[-1]
def empty(self):
return not self.input and not self.output- Push: O(1)
- Pop/Peek: Amortized O(1) - each element transferred at most once
- Space: O(n)
- Lazy transfer - only move elements when output is empty
- Amortized analysis - expensive operations happen infrequently
- Double reversal - two LIFO stacks simulate FIFO queue