Intermediate · easy · stack, queue, design
Implement Queue Using Stacks
The challenge
Implement a first-in, first-out queue with push, pop, peek and empty, using only two stacks and only stack operations: push to the top, pop from the top, look at the top and check the size. Every operation must take O(1) amortized time.
Example
push(1), push(2)
peek() -> 1
pop() -> 1
push(3)
pop() -> 2
pop() -> 3
empty() -> trueIdea: new items go onto the in stack. To take one out, look at the out stack: if it is empty, pour the whole in stack into it, one pop at a time. Pouring flips the order and leaves the oldest item on top. Pour only when out is empty, never before, or newer items would jump ahead of older ones. Each item moves from in to out at most once, so n operations cost O(n) in total: O(1) amortized each.
The solution
# Implement Queue Using Stacks - ayotl.dev
class Queue:
def __init__(self):
# new items go in, old ones go out
self.inp, self.out = [], []
def push(self, x):
self.inp.append(x)
def _pour(self):
# only when out is empty: pouring
# flips the order, oldest on top
if not self.out:
while self.inp:
self.out.append(
self.inp.pop())
def pop(self):
self._pour()
return self.out.pop()
def peek(self):
self._pour()
return self.out[-1]
def empty(self):
return not (self.inp or self.out)
q = Queue()
q.push(1)
q.push(2)
print("peek", q.peek())
print("pop", q.pop())
q.push(3)
print("pop", q.pop())
print("pop", q.pop())
e = q.empty()
print("empty", "true" if e else "false")
$ python3 implement_queue_using_stacks.py
peek 1
pop 1
pop 2
pop 3
empty true