mediumArraysSortingIntervals
Merge Overlapping Intervals
Merge a list of time ranges so that no two overlap. A practical problem behind calendars and booking systems, and a favourite for testing sorting logic.
By Deepak KumarTests checked by DeepakJavaScript or Python
Given a list of intervals [start, end] (with start <= end), merge all intervals that overlap and return the merged list sorted by start.
Intervals that only touch, such as [1, 3] and [3, 5], count as overlapping.
Examples
Example 1
Input: intervals = [[1, 3], [8, 10], [2, 6], [15, 18]] Output: [[1, 6], [8, 10], [15, 18]] Why: [1, 3] and [2, 6] overlap
Example 2
Input: intervals = [[1, 4], [4, 5]] Output: [[1, 5]] Why: Touching intervals merge
Constraints
1 <= intervals.length <= 10^40 <= start <= end <= 10^4
Hints
Hint 1
Overlaps are easy to spot if the intervals are in order. In which order?
Hint 2
After sorting by start, compare each interval with the last merged one: extend it, or start a new one.
Solution
Show the solution (try it yourself first)
Approach: sort, then sweep
Sort the intervals by their start. Then any interval that overlaps the previous merged block must start at or before that block's end. Walk through the sorted list: if the current interval starts at or before the end of the last merged interval, extend that end to the larger of the two ends; otherwise start a new block. Taking the maximum matters when one interval swallows the next, as in [1, 10] followed by [2, 3]. Copy the input before sorting if the caller's list must not change.
def merge_intervals(intervals):
out = []
for s, e in sorted(intervals):
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return outComplexity
Time O(n log n) for the sort; the sweep is O(n). Space O(n) for the output. Follow-up: inserting one new interval into an already merged, sorted list can be done in O(n) without re-sorting.