Sub topic 8
Interval Partitioning: Scheduling with the Fewest Rooms
This chapter assumes you can write Python functions with loops, know how heapq works as a min-heap, and are comfortable with proof by contradiction. It also builds on the earlier chapter on activity selection. That chapter picked the most intervals that fit in one room. This one fits every interval into as few rooms as possible.
The problem
You are given n intervals, such as lectures with start and end times. You must place every interval in a room so that no two intervals in the same room overlap. The goal is to use as few rooms as possible.
We treat intervals as half-open, [start, end). A lecture ending at 11 and another starting at 11 can therefore share a room. This convention matters for the code, and we come back to it under edge cases.
Activity selection could throw intervals away. Interval partitioning has to keep all of them, so the question changes from "which intervals?" to "how many rooms?"
A lower bound that tells you when to stop
Define the depth of a set of intervals as the largest number of intervals that contain any single point in time. If three lectures are all running at 9:30, you need at least three rooms, because those three must go in different rooms. So for any valid schedule:
- rooms used ≥ depth
Depth is a structural lower bound. No clever assignment can beat it. The greedy algorithm below always uses exactly depth rooms, and that is the core of its correctness proof. Lower bounds like this are a common shape for greedy proofs: find a quantity every solution must respect, then show the greedy solution matches it.
You can compute depth directly with a sweep over sorted start and end events:
def depth(intervals):
# (time, -1) sorts before (time, +1): an interval ending at t
# frees its slot before one starting at t takes a slot.
events = [(s, 1) for s, _ in intervals] + [(e, -1) for _, e in intervals]
events.sort()
current = best = 0
for _, delta in events:
current += delta
best = max(best, current)
return best
lectures = [(9, 11), (9, 13), (9, 11), (11, 13), (11, 14),
(13, 15), (13, 15), (14, 16), (15, 17), (15, 17)]
print(depth(lectures)) # 3The sweep tells you how many rooms you need. It does not tell you which interval goes in which room. The greedy algorithm does both.
The greedy algorithm
- Sort intervals by start time.
- For each interval, if some existing room is free (its last interval ended at or before this start), put the interval there.
- Otherwise, open a new room.
To find a free room quickly, keep a min-heap of the times when each room becomes free. The room at the top of the heap frees up earliest. If even that room is still busy, every room is busy.
The version below returns the room count and the room assigned to each interval:
import heapq
def assign_rooms(intervals):
order = sorted(range(len(intervals)), key=lambda i: intervals[i][0])
free_at = [] # min-heap of (end_time, room_id)
room_of = [None] * len(intervals)
rooms = 0
for i in order:
start, end = intervals[i]
if free_at and free_at[0][0] <= start:
_, room = heapq.heappop(free_at)
else:
room = rooms
rooms += 1
room_of[i] = room
heapq.heappush(free_at, (end, room))
return rooms, room_of
lectures = [(9, 11), (9, 13), (9, 11), (11, 13), (11, 14),
(13, 15), (13, 15), (14, 16), (15, 17), (15, 17)]
print(assign_rooms(lectures))
# (3, [0, 1, 2, 0, 2, 0, 1, 2, 0, 1])If you only need the count, the heap can hold bare end times, and heapq.heapreplace does the pop and push in one step:
import heapq
def min_rooms(intervals):
ends = []
for start, end in sorted(intervals):
if ends and ends[0] <= start:
heapq.heapreplace(ends, end)
else:
heapq.heappush(ends, end)
return len(ends)
print(min_rooms([(0, 30), (5, 10), (15, 20)])) # 2The heap never shrinks, so its final size equals the number of rooms opened.
Why it is optimal
Claim: the greedy algorithm uses exactly d rooms, where d is the depth.
Proof. Say greedy opens room number k while processing interval I = [s, e). It opens a new room only because all k − 1 existing rooms are busy at time s. Each busy room holds an interval that ends after s. Because we process in start-time order, each of those intervals also started at or before s. So each one contains the point s. Together with I, that gives k intervals that all contain s, so d ≥ k. This holds for every room greedy opens, including the last one. So greedy uses at most d rooms. Every valid schedule uses at least d rooms, so greedy is optimal. ∎
Greedy also never places two overlapping intervals in one room, because it reuses a room only when that room's last interval has ended. The output is therefore always valid.
The proof never uses the fact that we picked the earliest-free room. In start-time order, any free room works. The heap only makes finding a free room fast. That freedom disappears if you change the sort order, as the next section shows.
Common errors
Sorting by end time
Activity selection sorts by end time, so it is tempting to do the same here. With end-time order, the proof breaks: the busy intervals at time s might have started after s, so they don't all contain s. Here is a concrete failure:
import heapq
def heap_rooms(intervals, key):
ends = []
for start, end in sorted(intervals, key=key):
if ends and ends[0] <= start:
heapq.heapreplace(ends, end)
else:
heapq.heappush(ends, end)
return len(ends)
tricky = [(0, 4), (2, 6), (6, 10), (5, 12)]
print(heap_rooms(tricky, key=lambda iv: iv[0])) # 2 (start order: optimal)
print(heap_rooms(tricky, key=lambda iv: iv[1])) # 3 (end order: wrong)In end order, (6, 10) is processed before (5, 12). It takes the room freed at 4, which leaves only the room freed at 6. Then (5, 12) cannot fit anywhere, and greedy opens a third room even though the depth is 2.
Getting the boundary comparison wrong
The test ends[0] <= start encodes half-open intervals. If your intervals are closed, [start, end], then a meeting ending at 11 conflicts with one starting at 11, and the test must be ends[0] < start. Using the wrong comparison gives an answer that is off by one or more rooms whenever endpoints touch. The depth sweep has the same dependency: with closed intervals, starts must sort before ends at equal times.
Checking only the most recently opened room
Some implementations compare the new interval against the last room opened, or keep a single "last end" variable as in activity selection. That misses rooms that freed up earlier. You need the minimum end time over all rooms, which is exactly what the heap provides.
Complexity and alternatives
| Approach | Time | Gives assignment? | Notes |
|---|---|---|---|
| Greedy with min-heap | O(n log n) | Yes | Sort plus n heap operations |
| Greedy, linear scan of rooms | O(n log n + n·d) | Yes | Fine when depth `d` is small |
| Event sweep (`depth`) | O(n log n) | No | Count only. Easy to extend to "peak load" questions |
| Two sorted arrays of starts and ends | O(n log n) | No | Two-pointer variant of the sweep |
Edge cases
- Empty input: both functions return 0 rooms.
assign_rooms([])returns(0, []). - Zero-length intervals such as
(5, 5): under half-open semantics they contain no point, yet the greedy still assigns them a room. The sweep sorts their end event before their start event, so they add nothing to depth. If your domain treats them as real events, define the semantics explicitly. - Identical intervals:
kcopies of the same interval needkrooms, and greedy opens exactlyk. - Ties in start time: the order among equal starts does not affect the room count. The proof only needs non-decreasing start order.
- Floating-point times: equality checks at boundaries can misbehave. Use integer minutes or
fractions.Fractionwhen touching endpoints matter.
Exercise
Run start-order greedy (the assign_rooms function) by hand on [(1, 3), (2, 5), (4, 6), (5, 8), (7, 9)] with half-open intervals. How many rooms does it use, which room does each interval get, and what is the depth?
Show answer
The intervals are already in start order. (1,3) opens room 0. (2,5) overlaps it and opens room 1. (4,6): room 0 is free at 3, so it goes to room 0, which is now free at 6. (5,8): room 1 is free at 5, so it goes to room 1, now free at 8. (7,9): room 0 is free at 6, so it goes to room 0. Greedy uses 2 rooms with assignment [0, 1, 0, 1, 0]. The depth is 2. For example, (2,5) and (4,6) both contain time 4, and no point lies in three intervals. So 2 rooms is optimal.
Exercise
Your meeting data uses closed intervals: a meeting [10, 11] and a meeting [11, 12] cannot share a room. What exactly must change in min_rooms and in depth?
Show answer
In min_rooms, change the reuse test from ends[0] <= start to ends[0] < start, so that a room whose meeting ends at 11 cannot host one starting at 11. In depth, starts must be counted before ends at equal times. Encode start events as (s, -1) and end events as (e, +1), then add -delta to the running count, or use another tie-break that puts starts first. The meetings [10, 11] and [11, 12] then count as overlapping at time 11.
Exercise
The correctness proof says that, in start-time order, picking any free room works. Explain why choosing the room that freed up most recently instead of earliest still gives an optimal count, and why that freedom fails with end-time order.
Show answer
The proof only uses the fact that a new room is opened when all existing rooms are busy at the new start time s. In start order, every interval in a busy room started at or before s and ends after s, so it contains s. Opening room k therefore implies depth ≥ k, whichever free room was chosen earlier. In end-time order, a busy room may hold an interval that starts after s, so it does not contain s and the depth bound fails. The example [(0,4), (2,6), (6,10), (5,12)] shows that the room choice then changes the count: end-order greedy uses 3 rooms, but 2 are enough.