Maximum non-overlapping intervals: which greedy sort order works?
Question
You have one auditorium and a list of talk requests (start, end) with start < end. Intervals are half-open [start, end), so [1, 3) and [3, 5) do not overlap and can both run.
Write max_non_overlapping(intervals) to return the maximum number of talks you can schedule in that single room in O(n log n) time.
talks = [(0, 10), (1, 4), (4, 7), (3, 5), (7, 10)] max_non_overlapping(talks) # 3 max_non_overlapping([(1, 3), (3, 5)]) # 2 max_non_overlapping([]) # 0
def max_non_overlapping(intervals): ...
Show hints (3)
- "TEST WRONG ORDERS"
Try sorting
talksby earliest start ((0, 10)goes first) and by shortest length ((3, 5)goes first). How many talks survive under each rule? - "FREE THE ROOM EARLY"
You want as much time left as possible for later talks. Which single number tells you when the room opens up again?
- "SORT BY END TIME"
Sort by
endascending and keeplast_end = float("-inf"). Pick every interval withstart >= last_endand updatelast_end = end.
Show checked explanation
Sort the intervals by their end time ascending, then greedily pick every interval whose start >= last_end. Picking the talk that finishes first always leaves the most remaining time for later talks. Sorting by start time or duration fails on simple schedules. Time is O(n log n).
def max_non_overlapping(intervals): chosen = 0 last_end = float("-inf") for start, end in sorted(intervals, key=lambda x: x[1]): if start >= last_end: chosen += 1 last_end = end return chosen talks = [(0, 10), (1, 4), (4, 7), (3, 5), (7, 10)] print(max_non_overlapping(talks)) print(max_non_overlapping([(1, 3), (3, 5)])) print(max_non_overlapping([]))
3 2 0
Code and edge cases run on CPython 3.12.10; official documentation links checked. Checked by an editor other than the author.
Walkthrough
Three greedy sort orders look tempting at first glance. On talks = [(0, 10), (1, 4), (4, 7), (3, 5), (7, 10)], only one reaches the maximum of 3:
| sort order | chosen talks | count |
|---|---|---|
| earliest start | (0, 10) | 1 |
| shortest duration | (3, 5), (7, 10) | 2 |
| earliest end | (1, 4), (4, 7), (7, 10) | 3 |
Earliest start fails because (0, 10) starts first yet hogs the room all day. Shortest duration fails because (3, 5) lasts only 2 hours, but it straddles time 4 and blocks both (1, 4) and (4, 7).
Why does earliest end always work? Take any optimal schedule and look at its first talk X. Let E be the talk with the earliest end time overall. Because E finishes no later than X, swapping X out for E cannot clash with any later talk in that optimal schedule. You still have the same number of talks, and at least as much free time afterward. Repeating that choice on the remaining compatible talks builds an optimal schedule.
Watch the boundary check. Because talks are half-open [start, end), a talk ending at 3 frees the room at 3. Using start >= last_end accepts both (1, 3) and (3, 5) for a count of 2. Starting last_end at float("-inf") also handles negative timestamps safely.
Do not mix this up with the meeting-rooms question. Meeting rooms must host all talks and asks for the fewest rooms needed (peak overlap, which is 3 rooms for talks). Here you have one room and drop overlapping talks to keep the most you can.
Sorting takes O(n log n) time and O(n) space, followed by an O(n) linear scan.
Common mistakes
- Sorting by start time or duration. On
talks, earliest start gets 1 and shortest duration gets 2, both missing the optimal 3. - Writing
start > last_endfor half-open intervals. Back-to-back talks[(1, 3), (3, 5)]then return 1 instead of 2. - Initializing
last_end = 0. Negative timestamps like[(-5, -2), (-2, 1)]fail thestart >= 0check and get dropped. Usefloat("-inf"). - Confusing this with minimum meeting rooms. Hosting all meetings counts peak overlap; here you select a maximum subset for one room.
Follow-up questions
- "How many intervals must you remove so the rest do not overlap?" It is the exact complement:
len(intervals) - max_non_overlapping(intervals). Ontalks, keeping 3 talks means removing at least 2 ((0, 10)and(3, 5)). - "What if touching intervals like [1, 3] and [3, 5] count as overlapping?" Change
start >= last_endtostart > last_end. Then[(1, 3), (3, 5)]returns 1, andtalksdrops from 3 to 2 (such as(1, 4)and(7, 10)). - "What if each talk has a profit and you want maximum total profit?" Greedy by end time fails. Two short talks worth 1 each beat one overlapping talk worth 10 by count, not profit. Sort by end time and use dynamic programming with binary search (
bisect_right) in O(n log n).
What a strong answer covers
Gives concrete counterexamples showing why start time and duration fail, and explains the exchange argument for earliest end in plain words. Clarifies the touching-boundary rule [1, 3) and [3, 5), and separates single-room selection from minimum meeting rooms.
Open in interactive practice deck →