Skip to content
BytePatterns

Interval Scheduling

Greedy: lesson 2 of 5

Sort by finishing time and the room books itself.

Lesson 2 of 5 · 5 min

Interval Scheduling

Step 1 of 10

Five bookings for one room. Take as many as possible without two of them overlapping.

The Idea

You want as many non-overlapping jobs as possible from one room. Sort by finishing time, then walk the list and take any job that starts at or after the last one you took.

Finishing early is the only thing that matters, because the job that ends soonest leaves the largest slice of the day for everything else. Duration and start time are both red herrings.

Real-World Example

A single edit bay at a post-production house. Six clients want it today; the scheduler accepts whichever booking clears the bay earliest, so the most clients get served — not the one who asked first, and not the longest job.

The Code

jobs = [(1, 4), (3, 5), (0, 6), (5, 7), (8, 10)]
jobs.sort(key=lambda j: j[1])        # earliest finishing time first
taken, last_end = [], float("-inf")
for s, e in jobs:
    if s >= last_end:                # no clash with what is already booked
        taken.append((s, e))
        last_end = e                 # the room is free again at e
print(taken)
print(len(taken))

Python

Your turn

Put the steps in the right order.

  1. Accept the job and move the free-from time to its end
  2. Sort every job by its finishing time
  3. Skip the job, because it overlaps what is already booked
  4. Start with the room free from minus infinity
  5. Compare the next job's start against the free-from time

Mini quiz

1 / 3

Which key makes interval scheduling greedy correct?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.