Lessons 16–20 · About 60 min per lesson
Stacks, queues and priority queues
Choose a container based on the processing order the task requires.
Lesson breakdown
- Lesson 16
Use a stack to match brackets and explain last-in-first-out.
- Lesson 17
Use a queue to serve requests in arrival order.
- Lesson 18
Manipulate both ends of a deque and identify when it is useful.
- Lesson 19
Use priority_queue to keep the most urgent item available.
- Lesson 20
Maintain a fixed number of largest elements with a min-heap.
Worked example
Values arrive as 7, 1, 5 and 9. Keep only the largest two.
How to solve it
Insert each value and pop the minimum whenever the heap grows past 2, leaving 7 and 9.
Assignment
Maintain the largest k values in a stream with a min-heap. Support k=0 and duplicates.
Check your result
k=2, [7,1,5,9] retains [7,9]; k=2, [5,5,3] retains [5,5]; k=0 retains nothing.