Merge intervals
Given a list of intervals, each one a start and an end, merge every pair that overlaps and return the intervals that remain. They arrive in no particular order, and intervals that merely touch — one ending exactly where the next begins — count as overlapping.
Examples
Example 1
- Input
- intervals = [[1, 3], [8, 10], [2, 6], [15, 18]]
- Output
- Sorted by where they start, the four run [1, 3], [2, 6], [8, 10], [15, 18]. Only the first pair touches — 2 falls inside 1–3 — so those merge into [1, 6], while 8 and 15 each begin after the interval before them has ended.
[[1,6],[8,10],[15,18]]
Example 2
- Input
- intervals = [[1, 4], [4, 5]]
- Output
- Touching counts as overlapping — 4 is the end of one and the start of the next.
[[1,5]]
The Code
function merge(intervals) {
const sorted = intervals.slice().sort((a, b) => a[0] - b[0]);
const merged = [];
for (let i = 0; i < sorted.length; i++) {
const last = merged[merged.length - 1];
if (!last || last[1] < sorted[i][0]) {
merged.push([sorted[i][0], sorted[i][1]]);
} else {
last[1] = Math.max(last[1], sorted[i][1]);
}
}
return merged;
}
merge([[1, 3], [8, 10], [2, 6], [15, 18]]);Explanation
Sorted by start, each interval meets only the one being built: it either pushes that one’s end out or closes it and begins a new one.
- 1
mergedis empty, so there is no interval being built yet and the first one of the sorted list is pushed as it stands.1–302–618–10215–183merged=[]last=none
merged → [[1, 3]]
- 2
sorted[1]is 2–6.last[1]is 3, which is not less than the 2 it starts at, so they overlap — andlast[1]becomes the larger of the two ends, 6. That assignment goes through a reference:lastis the interval held inmerged, somergedchanges with it and there is nothing to put back.1–608–10115–182merged=[[1, 3]]last=1–3
last[1] = 6 · merged → [[1, 6]]
- 3
sorted[2]is 8–10, andlast[1]is 6, which is less than 8. Nothing overlaps, so 1–6 is finished and 8–10 is pushed as a new interval — which makes it the newlast.1–608–101merged=[[1, 6]]last=1–6
merged → [[1, 6], [8, 10]]
- 4
sorted[3]is 15–18 andlast[1]is 10, so it is pushed too. Four intervals have come out as three.1–608–10115–182merged=[[1, 6], [8, 10]]last=8–10
merged → [[1, 6], [8, 10], [15, 18]]
More like this
All arrays & loops examples (10) →- FizzBuzz The classic warm-up — Fizz, Buzz, or the number.
- Array maximum Track the largest seen so far in a single pass.
- Two sum Remember every number you’ve seen; check for its complement.
- Product except self Everything to the left of a position, times everything to its right.
- Majority element Pair off disagreeing votes; the majority always survives.
- Top K frequent Bucket values by their count, then read the buckets from the top.