Learn / Heaps and priority queues

Scheduling

Many scheduling problems sort the jobs by start time and keep a min heap of what is running, keyed by end time. Before a job starts, pop every job that has already ended. The heap size is then the number of jobs running at once, and its top is the next to finish.

How to recognise it

  • Intervals, meetings or jobs with start and end times.
  • The question asks how many rooms, machines or workers are needed at once.
  • Tasks must be picked by deadline, cost or profit as time moves on.

Rooms needed at once

sort meetings by start
heap = empty min heap of end times
for (start, end) in meetings:
    while heap and heap.top <= start: pop      # those rooms are free again
    push end
    rooms = max(rooms, heap size)

Whether a meeting that ends at 4 frees its room for one starting at 4 depends on the problem; this guide treats end <= start as free.

Other heap-driven schedules

  • Greedy by deadline: sort by deadline, keep a heap of chosen durations, and drop the longest when the total runs past the current deadline.
  • Most profit first: at each moment, take the best job that has become available.
  • Cooldowns: like rearranging letters, always run the most frequent task allowed, and hold each used task back for its cooldown.

The sheets this guide follows have no problems for this pattern yet, so the lesson stops at the ideas.

Common mistakes

  • Popping only one finished meeting instead of all of them.
  • Forgetting to sort by start time.

Problems

No problems listed for this pattern yet.

Check yourself

Meetings [1, 4], [2, 5], [7, 9]. How many rooms are needed?

What does the min heap hold in the meeting-rooms method?

Why sort by start time first?