function merge(intervals) {◄intervals.sort((a, b) => a[0] - b[0]);
const res = [];
let cur = intervals[0];
for (let i = 1; i < intervals.length; i++) {const next = intervals[i];
if (next[0] <= cur[1]) // overlap
cur[1] = Math.max(cur[1], next[1]);
else { // gapres.push(cur);
cur = next;
}
}
res.push(cur);
return res;
}
Picture each interval as a bar on a number line. Two bars overlap when one starts before the other ends — and merging them just means taking one bar from the earliest start to the latest end.
The key trick is to sort by start first. Once sorted, any intervals that overlap are guaranteed to be neighbours, so you never have to look backwards — you only compare each interval with the single "current" interval you are building.
Walk through the sorted list keeping one running interval, cur. For the next interval: if it starts at or before cur.end, it overlaps, so absorb it by pushing cur.end out to the larger of the two ends.
If it starts after cur.end, there is a gap — cur is finished and can never grow again, so save it and let the next interval become the new cur.
Why max(cur.end, next.end)? Because next might be completely inside cur (e.g. [1,10] then [2,3]); taking the max keeps the longer reach instead of shrinking it.