Intervals
Lay every meeting of a shared day on one timeline in start order. Meetings that overlap or touch fuse into one busy block. What is left is the day’s true shape, with every gap visible.
2 · Watch
Intervals in 60 seconds
3 · Now you drive
Merge Intervals
4 · Your turn
Start from this
if (intervals.length === 0) return [];
// Sort by start, so overlaps end up side by side.
intervals.sort((a, b) => a[0] - b[0]);
const out = [intervals[0]];
for (const [start, end] of intervals.slice(1)) {
const last = out[out.length - 1];
// Overlap: extend the last one to the later end.
if (start <= last[1]) last[1] = Math.max(last[1], end);
// No overlap: this one starts a new interval.
else out.push([start, end]);
}Easy ways to go wrong
- Forgetting to sort first.
- Replacing the end with the new end. Take the max, since one may contain the other.
- Deciding whether touching ends count as overlap. Read the problem.
- Sorting by start when you must remove the fewest. Sort by end, so you keep whichever finishes first.
- Easy01
Meeting Rooms
LeetCode PremiumWarm-up: sort by start; any overlap means a clash.
Sort by start. Any overlap means a clash.
- Time
- O(n log n)
- Space
- O(1)
- Medium02
Merge Intervals
The one you just watched. Write it from memory.
Sort by start. Each range either extends the last one or starts a new one.
- Time
- O(n log n)
- Space
- O(n)
- Medium03
Insert Interval
Slide the new interval into its sorted slot, then merge.
Copy what’s before, merge what overlaps, copy the rest.
- Time
- O(n)
- Space
- O(n)
- Medium04
Non-overlapping Intervals
Count the overlaps to remove instead of merging them.
Keep whichever ends first. It leaves the most room.
- Time
- O(n log n)
- Space
- O(1)
Also works with Greedy.
- Medium05
Meeting Rooms II
LeetCode PremiumTrack how many meetings run at once; keep the peak.
Sort starts and ends apart and track how many run at once.
- Time
- O(n log n)
- Space
- O(n)
Also works with Heaps or Greedy.