Meetings, bookings, IP ranges, price windows — interval problems are everywhere in real systems, and they all start with the same two moves.
Move 1: know the overlap test
// [a1, a2] and [b1, b2] overlap when: a1 <= b2 && b1 <= a2 // each starts before the other ends. Draw it once; remember it forever.
Move 2: sort by start, then sweep
function mergeIntervals(intervals) {
intervals.sort((a, b) => a[0] - b[0]); // sort by start
const out = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const last = out[out.length - 1];
const cur = intervals[i];
if (cur[0] <= last[1]) {
last[1] = Math.max(last[1], cur[1]); // overlap → extend
} else {
out.push(cur); // gap → start new interval
}
}
return out;
}
// [[1,3],[2,6],[8,10]] → [[1,6],[8,10]]After sorting, you only ever compare with the last merged interval — earlier ones can't overlap anything new. That insight is the whole pattern.
The famous variants
- Insert interval — add one interval into a sorted list, merging as needed.
- Meeting rooms I — "can one person attend all meetings?" = does anything overlap after sorting?
- Meeting rooms II — "minimum rooms needed" = max simultaneous overlaps (sort starts and ends separately, sweep with a counter).
Spot it when…
- Input is pairs of [start, end]. That's it — the word "interval", "meeting", "range", or "booking" is the giveaway.
Complexity: O(n log n) from the sort; the sweep is O(n). Interviewers expect you to say the sort dominates. Next: Binary Search as a pattern — more than finding values.