Algorithms · Sort, then sweep
Meeting Rooms
Can one person attend every meeting?
The problem
Each meeting is [start, end]. Return True if no two meetings overlap, so one person could attend them all. A meeting that ends at 5 doesn’t clash with one that starts at 5.
no_clashes([[0, 30], [5, 10], [15, 20]])→Falseno_clashes([[7, 10], [2, 4]])→TrueStart with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def no_clashes(meetings):take [start, end] for each meeting for i in range(len(meetings)):pick a meeting for j in range(i + 1, len(meetings)):and every later one a, b = meetings[i], meetings[j]the two meetings if a[0] < b[1] and b[0] < a[1]:do they overlap? return Falsea clash return Trueno two overlapNow ask: what if there were a billion?
Google’s Spanner database treats time itself as an interval [earliest, latest], because clocks are never perfectly in sync. It waits out any overlap before it commits, so events across the world stay in order.
Aim for O(n log n)🌱 warm-up
Think it through
If meetings were sorted by start time, which pairs could clash?
- Any pair
- Only neighbours in the sorted order
Show the answer
Only neighbours in the sorted order. If a meeting doesn’t overlap the one just before it, it can’t overlap anything earlier either. Sorting turns every-pair into neighbour checks.
One ends at 5 and the next starts at 5. Clash?
- Yes
- No
Show the answer
No. Read the rule for the edge carefully: here touching is fine, so the check is start < previous end. Boundaries are where most interval bugs live.
Stuck? 3 nudges, smallest first
- If the meetings were in order of start time, where could a clash possibly be?
- Only between neighbours! Sort by start time, then compare each meeting with the one just before it.
meetings = sorted(meetings), then for eachi, checkmeetings[i][0] < meetings[i - 1][1].
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def no_clashes(meetings):take [start, end] for each meeting meetings = sorted(meetings)lay them out from earliest start to latest for i in range(1, len(meetings)):walk through them in order if meetings[i][0] < meetings[i - 1][1]:starts before the previous one ends? return Falsea clash return Trueno two overlapWhere it’s used for real
Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.