Implement Queue using Stacks
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Build a first-in-first-out queue using only stacks (last-in-first-out).
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Pushing is easy. Why is popping the oldest item hard with one stack?
- Hint 2What happens to the order when you pour one stack into another?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Two piles of plates. New plates go onto the "in" pile. The person at the counter always needs the OLDEST plate, which is at the bottom of the in-pile. When the "out" pile is empty, pour the whole in-pile onto the out-pile: the order flips, so the oldest plate is now on top. Keep serving from the out pile and only pour again when it runs out.
- The obvious way
On every pop, pour everything into a helper stack and back: O(n) per pop.
- The key insight
Use an in-stack for pushes and an out-stack for pops. Only when the out-stack is empty, move every item from the in-stack to it (this reverses them so the oldest is on top). Each item is moved at most once, so pops cost O(1) on average.
- The algorithm
- push: put the item on the in-stack.
- pop/peek: if the out-stack is empty, move all items from the in-stack to it one by one.
- Then take (or look at) the top of the out-stack.
- empty: true when both stacks are empty.
Watch it run
Examplepush(1), push(2), peek(), pop(), empty()
push 1 and push 2 go onto the in pile: [1, 2] (2 on top).
in: 1, 2 out: (empty)
Where people slip
- Pour the in-stack ONLY when the out-stack is empty; pouring earlier breaks the order.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
class MyQueue:
def __init__(self):
self.in_pile = [] # new items land here
self.out_pile = [] # items leave from here, oldest on top
def push(self, x):
self.in_pile.append(x)
def _fill_out(self):
if not self.out_pile: # only pour when it has run out
while self.in_pile:
self.out_pile.append(self.in_pile.pop())
def pop(self):
self._fill_out()
return self.out_pile.pop()
def peek(self):
self._fill_out()
return self.out_pile[-1]
def empty(self):
return not self.in_pile and not self.out_pileNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.