1. Sort by start
Sorting by start groups overlapping intervals together.
intervals.sort((a, b) => a[0] - b[0])Typorithm · medium
Step 1 of 8 · intro card
Intervals
Sort by start, then sweep; if the next interval overlaps the last merged one, extend its end, otherwise append it.
Sorting by start guarantees that any interval overlapping a previous one is adjacent in the order.
Compare each interval with the last merged interval: if its start is within that interval, they overlap.
On overlap, extend the last interval's end to the maximum of the two; otherwise, start a new merged interval.
Sort intervals by start.
Overlap when start <= last end.
Extend end with Math.max.
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const merged = [];
for (const [start, end] of intervals) {
const last = merged[merged.length - 1];
if (last && start <= last[1]) {
last[1] = Math.max(last[1], end);
} else {
merged.push([start, end]);
}
}
return merged;
}Connect each part of the code to the concept before you type.
Sorting by start groups overlapping intervals together.
intervals.sort((a, b) => a[0] - b[0])Compare each interval against the most recently merged one.
const last = merged[merged.length - 1]An overlap occurs when the new start is within the last interval.
if (last && start <= last[1]) {Stretch the last interval's end to cover the overlap.
last[1] = Math.max(last[1], end)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.