Meeting rooms II
StopHeap
- CH1 heap
27/27
Sort by start, and keep the end times of meetings in progress on a heap. Its biggest size is the rooms you need.
Step through it →Sort intervals by start, then sweep once: each one can only overlap the last interval kept, so one comparison decides whether to merge.
Sorted by start, a new interval either reaches the last merged one and stretches it, or starts past its end and begins a new one. So the last one is the only one it could overlap.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
They share the point 4. Comparing with < instead of ≤ would keep them apart.
Sort by start, and keep the end times of meetings in progress on a heap. Its biggest size is the rooms you need.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
def merge(intervals): intervals = sorted(intervals, key=lambda iv: iv[0]) merged = [] for start, end in intervals: if merged and start <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], end) else: merged.append([start, end]) return merged