Merge Intervals
Problem (restated)
Given intervals [start, end], merge all overlapping intervals and return the non-overlapping result covering the same ranges.
Intuition
Sort by start. Scan and either merge into the current open interval or push a new one when there is a gap.
Approaches
Sort by start + merge
Tested onlyIdea. Sort intervals by start. Keep a list of merged. If next.start ≤ last.end, last.end = max(last.end, next.end); else append next.
Walkthrough. [[1,3],[2,6],[8,10]] → merge first two to [1,6], then append [8,10].
Trade-offs. Sorting dominates. In-place tricks exist but are rarely worth it in interviews.
export function merge(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0]! - b[0]!);
const res: number[][] = [];
for (const interval of intervals) {
const last = res[res.length - 1];
if (!last || interval[0]! > last[1]!) res.push([...interval]);
else last[1] = Math.max(last[1]!, interval[1]!);
}
return res;
}
export function merge(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0]! - b[0]!);
const res: number[][] = [];
for (const interval of intervals) {
const last = res[res.length - 1];
if (!last || interval[0]! > last[1]!) res.push([...interval]);
else last[1] = Math.max(last[1]!, interval[1]!);
}
return res;
}
Template connection
Flagship intervals problem. sort then linear merge.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?