Boss lesson · Unit 02
A queue from two stacks
Pour once, pop many times: amortised O(1)
What you practise
- Amortised O(1) per operation
Try a question from this lesson
Pick one
You only have stacks. You push 1, 2, 3 onto stack A, then pop every item from A and push it onto stack B. What is on top of B?
Correct answer
1
Why
Pouring reverses: 3 leaves A first and ends up at the bottom of B, and 1 leaves last and ends up on top. The oldest item is now the easiest to reach, which is what a queue needs.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
An in-stack and an out-stack
Build a queue from two stacks.
Enqueue: push onto the in-stack. Always.
Dequeue: pop from the out-stack. If the out-stack is empty, first pour the whole in-stack into it. The pour reverses the items, so the oldest lands on top.
Pour only when the out-stack is empty.
Concept
Amortised cost: pay once per item
Follow one item through its life: pushed onto the in-stack, poured once to the out-stack, popped. That is a fixed amount of work, whatever else is going on.
So n operations cost O(n) in total, even though one unlucky dequeue pours everything. Averaged over the sequence, each operation is O(1). That average is the amortised cost.
10 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 2× multiple choice
- 2× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.