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

  1. Lesson 16

    Use a stack to match brackets and explain last-in-first-out.

  2. Lesson 17

    Use a queue to serve requests in arrival order.

  3. Lesson 18

    Manipulate both ends of a deque and identify when it is useful.

  4. Lesson 19

    Use priority_queue to keep the most urgent item available.

  5. 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.