Merge Intervals
Merge all overlapping intervals into the fewest ranges
DSA, Medium, Intervals
Which structure or algorithm, and what does it cost.
A list ranges holds closed ranges [start, end] with start <= end. Two ranges overlap if they share at least one point, so [1,4] and [4,5] overlap. Return the smallest list of non-overlapping ranges that covers exactly the same points, sorted by start. The input is not sorted.
Examples
Constraints
- 0 <= number of ranges <= 100,000.
- -1,000,000,000 <= start <= end <= 1,000,000,000.
Your answer must contain
- The method and why it is correct; code; time and memory; a hand trace of example 1.
Target Aim for O(n log n) time.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Look at two ranges side by side. When do they overlap, and which single range replaces them?
Hint 2 the approach
Unsorted ranges can overlap in any order. Order them by start first, so a range can only overlap the one just before it.
Hint 3 the key step
Keep the last merged range. If the next start is at most its end, raise the end to the larger of the two ends. Otherwise begin a new range.
Walkthrough
Full walkthrough brute force to best
Brute force
Compare every pair, merge any two that overlap, and repeat until no pair overlaps. A chain like [1,2], [5,6], [2,5] needs more than one pass. Each pass is O(n^2), which is too slow for 100,000 ranges.
Better method
Sort the ranges by start, then compare each range with every merged range so far. Sorting helps, but the extra scan is wasted work, and the scan makes it O(n^2) in the worst case: only the last merged range can overlap the next one.
Best method
Sort by start. Now a range that overlaps the current merged range must come right after it, and nothing later can reach back before it. Keep the last merged range. For the next range, if its start is at most the last end, they overlap: set the last end to the larger of the two ends. Use the larger end, not a plain assignment, because the next range may sit entirely inside. If its start is greater than the last end, begin a new merged range. Writing "at most" instead of "less than" makes ranges that only touch merge, as the statement asks.
Hand trace
Sort example 1: [1,3], [2,5], [4,9], [12,14]. Take [1,3]: the output is [[1,3]]. Take [2,5]: 2 is at most 3, so the end becomes 5 and the output is [[1,5]]. Take [4,9]: 4 is at most 5, so the end becomes 9 and the output is [[1,9]]. Take [12,14]: 12 is more than 9, so a new range starts and the output is [[1,9],[12,14]].
Code
def merge(ranges):
out = []
for s, e in sorted(ranges):
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return outTime and memory
O(n log n) time, from the sort. The walk is O(n). O(n) memory for the output.
Common mistakes
- Skipping the sort. Unsorted input breaks the idea that only the last range can overlap.
- Testing that the next start is below the last end, not at or below it. Ranges like [2,6] and [6,8] then stay apart.
- Setting the end to the new range's end. With [0,20] then [3,4], this shrinks the range to [0,4]. Use the larger end.