Minimum Classrooms to Schedule All Lectures
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Tests whether a candidate can reframe a resource-allocation problem as peak interval overlap and handle half-open boundary conditions correctly.
A university needs to assign classrooms to a list of lectures. Each lecture occupies exactly one classroom for its entire duration, and no two lectures can share a classroom at the same time.
Given a list of lectures where each entry is [start, end], return the minimum number of classrooms required to hold every lecture without any conflicts.
Rules
lectures[i] = [start, end]withstart < end. A classroom is considered occupied fromstartup to, but not including,end.- A classroom that becomes free at time
tcan immediately host another lecture beginning at timet. - Any available classroom can be assigned to any lecture; physical location is not a factor.
Constraints
1 <= len(lectures) <= 10^50 <= start < end <= 10^9for every lecture
Examples
Example 1
Input: min_classrooms([[1, 4], [2, 5], [7, 9], [3, 6]])
Output: 3
Example 2
Input: min_classrooms([[1, 3], [3, 5], [5, 8]])
Output: 1
Example 3
Input: min_classrooms([[2, 10], [3, 4], [4, 6], [7, 8]])
Output: 2
Hints
Hint 1
Think about what the answer actually represents in terms of the lecture intervals — is there a simpler quantity you can compute directly?
Hint 2
Try converting each lecture into two timestamped events (one when it starts, one when it ends) and processing them in order. What does the running total tell you?
Hint 3
When a lecture ends and another begins at the exact same time, the order you process those two events changes the answer. Which order matches the problem rules, and does your sort handle it automatically?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reframing the problem
The minimum number of classrooms equals the maximum number of lectures running simultaneously. This is true in both directions:
- At least this many are needed. If
klectures all overlap at some moment, each requires its own room, so you need at leastk. - Exactly this many suffice. Assign rooms greedily in order of start time. Whenever a lecture begins, reuse any room that has just become free; otherwise open a new one. If no room were free at that moment, all existing rooms would be occupied simultaneously, which would already be the peak. Adding the new lecture would push the overlap above the peak — a contradiction. So the greedy never opens more rooms than the peak overlap.
This means you only need to find the peak overlap of the half-open intervals [start, end).
Sweep line
Convert each lecture [s, e] into two events: (s, +1) meaning a room is now taken, and (e, -1) meaning a room is now free. Sort all events by time and walk through them, maintaining a running count of occupied rooms. The highest value reached is the answer.
The critical detail is the tie-breaking rule at equal timestamps. When one lecture ends at time t and another starts at t, the end event must be processed first so the freed room is available for the incoming lecture. Sorting plain tuples (time, delta) handles this automatically: at equal times, -1 < +1, so release events always precede pickup events. No custom comparator is needed.
Why the running count is accurate
After processing all events at or before time t, cur equals the number of lectures with start <= t < end — exactly the lectures active at t under the half-open rule. Because releases at t are processed before pickups at t, a lecture ending at t is never counted alongside a lecture starting at t.
Complexity
- Time:
O(n log n)to sort2nevents; the linear sweep is dominated by the sort. - Space:
O(n)for the event list.
With n <= 10^5 this means at most 200,000 events, well within practical limits. Note that timestamps can be as large as 10^9, but they are only compared, never used as array indices, so no coordinate compression is required.
Walkthrough
lectures = [[2, 10], [3, 4], [4, 6], [7, 8]]
Sorted events and running count:
| Event | cur |
|---|---|
| (2, +1) | 1 |
| (3, +1) | 2 |
| (4, -1) | 1 |
| (4, +1) | 2 |
| (6, -1) | 1 |
| (7, +1) | 2 |
| (8, -1) | 1 |
| (10, -1) | 0 |
Peak is 2. At time 4, the release from [3, 4] is applied before the pickup for [4, 6]. Reversing that order would incorrectly yield a peak of 3.
Edge cases
- Single lecture: peak is 1, so the answer is 1.
- Back-to-back lectures with no gap: the tie-break keeps the count at 1, not 2.
- Identical lectures (e.g. three copies of
[1, 5]): all three+1events stack, giving 3. Correct. - One long lecture enclosing several short ones: only the simultaneous overlap matters; nesting is handled naturally.
Reference solution
from typing import List
def min_classrooms(lectures: List[List[int]]) -> int:
# Build one event per boundary: +1 when a lecture begins, -1 when it ends.
events = []
for s, e in lectures:
events.append((s, 1))
events.append((e, -1))
# Sorting tuples places (t, -1) before (t, +1) at equal timestamps,
# so a room freed at t is counted as available before a new lecture at t
# is counted as occupying it. This correctly models the half-open intervals.
events.sort()
cur = best = 0
for _, delta in events:
cur += delta
if cur > best:
best = cur
return best
Alternative approaches
Min-heap of end times. Sort lectures by start time. Maintain a min-heap of end times of currently occupied rooms. For each lecture, if the smallest end time is <= start, pop it (that room is free). Push the current lecture's end time. The largest heap size reached is the answer. Also O(n log n), and easier to extend if you need to track which room handles which lecture.
Two-pointer on sorted arrays. Sort starts and ends into separate arrays, then advance two pointers simultaneously — always advancing the end pointer first when end <= start. This avoids building explicit event tuples and is the most memory-efficient variant, though all three approaches give identical results.