Combine Overlapping Intervals
Greedy & IntervalsAuto-graded · 24 test casesLast updated
Tests interval merging through sorting and linear scanning, focusing on edge-case handling for touching and nested ranges.
Combine Overlapping Intervals
You receive a collection of intervals, each represented as a pair of integers [start, end]. Two intervals are considered overlapping if they share at least one point in common, including their boundaries. For instance, [1, 3] and [3, 5] overlap at point 3 and should combine into [1, 5].
Write a function that processes a list of such intervals and produces a new list where all overlapping intervals have been consolidated into single continuous ranges.
Constraints
1 <= intervals.length <= 10,0000 <= start < end <= 10^9- Each interval
[start, end]satisfiesstart < end
Notes
- Intervals that touch at endpoints must be merged
- An interval completely inside another should be absorbed
- The input may arrive in any order
Examples
Example 1
Input: combine_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])
Output: [[1, 6], [8, 10], [15, 18]]
Example 2
Input: combine_intervals([[1, 4], [4, 5]])
Output: [[1, 5]]
Hints
Hint 1
Consider how sorting the intervals by their starting points simplifies overlap detection
Hint 2
When intervals are sorted, you only need to check if each new interval overlaps with the most recently merged range
Hint 3
Remember that intervals touching at a single point (like [1,4] and [4,5]) count as overlapping
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Combine Overlapping Intervals
Approach
Detecting overlaps between arbitrary intervals requires comparing every pair, leading to O(n²) complexity. We can eliminate this inefficiency by ordering the intervals by their start positions first. Once sorted, any interval can only potentially overlap with the consolidated range that comes immediately before it in the sequence.
The algorithm proceeds as follows:
- Sort the intervals by start position (and by end position as a tiebreaker for consistency)
- Initialize the result list with a copy of the first sorted interval
- Iterate through remaining intervals:
- If the current interval's start is less than or equal to the last merged interval's end, they overlap or touch—extend the last merged interval's end to cover both ranges using
max(current_end, last_end) - Otherwise, a gap exists between them—append the current interval as a new separate range
- If the current interval's start is less than or equal to the last merged interval's end, they overlap or touch—extend the last merged interval's end to cover both ranges using
The key detail: we use <= rather than < because the problem specifies that intervals touching at a single point must be merged. For example, [1, 4] and [4, 5] should combine into [1, 5].
Why This Works
After processing the first k sorted intervals, our merged list maintains this property: it contains disjoint, sorted ranges whose union exactly equals the union of those k input intervals.
When intervals overlap (start <= merged[-1][1]): The current interval begins at or before the previous range ends. Taking max(merged[-1][1], end) produces their exact union. The max is critical—without it, an interval like [2, 5] could incorrectly shrink a larger range [1, 10] down to [1, 5].
When intervals don't overlap (start > merged[-1][1]): A gap exists. Because the list is sorted by start, every future interval will also have a start greater than the current gap, so no later interval can reach back to merge with the previous range. We safely finalize that range and begin a new one.
Complexity
- Time: O(n log n) dominated by sorting. The merging scan is O(n) with constant work per interval.
- Space: O(n) for the sorted list and output. Python's sort may use O(n) auxiliary memory internally.
Implementation
from typing import List
def combine_intervals(intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
ordered = sorted(intervals, key=lambda interval: (interval[0], interval[1]))
merged = [[ordered[0][0], ordered[0][1]]]
for start, end in ordered[1:]:
if start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
Trace example: For input [[1,3],[2,6],[8,10],[15,18]], after sorting we get the same order. We start with [[1,3]], then merge [2,6] to get [[1,6]], append [8,10] to get [[1,6],[8,10]], and finally append [15,18] for [[1,6],[8,10],[15,18]].