Consolidate Overlapping Ranges
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Tests ability to sort intervals and merge adjacent or overlapping ranges into a minimal disjoint set.
Consolidate Overlapping Ranges
You are given a collection of intervals, where each interval is represented as a pair [start, end]. Your task is to combine any intervals that overlap or touch into single, larger intervals, and return the resulting list of non-overlapping intervals.
Two intervals overlap if they share any point in common. Additionally, intervals that meet at a boundary point (for example, [1, 4] and [4, 5]) are considered overlapping and should be merged.
Write a function that takes a list of intervals and returns a new list containing only the merged, non-overlapping intervals that cover exactly the same range as the input.
Constraints
1 <= intervals.length <= 10^4- Each interval
[start, end]satisfies0 <= start <= end <= 10^4 - The input intervals may appear in any order
- Intervals that share only a boundary point are considered overlapping
Examples
Example 1
Input: consolidate_ranges([[1, 3], [2, 6], [8, 10], [15, 18]])
Output: [[1, 6], [8, 10], [15, 18]]
Example 2
Input: consolidate_ranges([[1, 4], [4, 5]])
Output: [[1, 5]]
Hints
Hint 1
Start by sorting the intervals. Once sorted by their start points, overlapping intervals will be adjacent in the list.
Hint 2
After sorting, iterate through the intervals and maintain the last merged interval. Check if the current interval overlaps with or touches the last merged one.
Hint 3
Remember that one interval can be completely contained within another. Use the maximum of the end points when merging to handle this case correctly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Consolidate Overlapping Ranges
Approach
The core insight is that once intervals are sorted by their starting points, any interval that can merge with the current working interval must appear immediately after it in the sorted sequence. This observation allows us to solve the problem with a single linear pass after sorting.
The algorithm proceeds in three steps:
-
Sort the intervals by their start values. This ensures that potentially overlapping intervals become adjacent in the array.
-
Initialize the result with a copy of the first interval. We copy it to avoid modifying the caller's data structure.
-
Process each remaining interval in order:
- If the current interval's start is less than or equal to the end of the last merged interval, they overlap or touch. Extend the last merged interval's end to be the maximum of its current end and the current interval's end.
- If there's a gap (current start is greater than the last merged end), the intervals don't overlap. Append the current interval as a new separate range.
The comparison uses <= rather than < because intervals that share only a boundary point are defined as overlapping and must be merged.
Why This Works
After sorting, we maintain an invariant: the merged list always contains the correctly consolidated intervals for all intervals processed so far, and these merged intervals are disjoint and sorted.
When we examine a new interval [s, e], we know its start s is at least as large as every start we've seen before due to sorting. This means it cannot reach back to any merged interval except possibly the last one. All earlier merged intervals have already been finalized—no future interval can bridge back to them.
Therefore, we only need to check against the last merged interval:
- If
s <= last_end, the intervals overlap or touch, so we extend the last interval's end to cover both ranges usingmax(last_end, e). Themaxis crucial for handling containment (e.g.,[1, 10]followed by[2, 5]must remain[1, 10], not shrink to[1, 5]). - If
s > last_end, there's a true gap, so we start a new merged interval.
By induction, this produces the correct minimal set of non-overlapping intervals.
Complexity
Time Complexity: O(n log n)
- Sorting dominates at O(n log n)
- The merging pass is O(n), visiting each interval once
Space Complexity: O(n)
- Sorting creates a new list in O(n) space
- The output can contain up to n intervals in the worst case (no overlaps)
- Python's Timsort may use O(n) auxiliary space during sorting
Implementation
from typing import List
def consolidate_ranges(intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
intervals = sorted(intervals, key=lambda interval: interval[0])
merged = [intervals[0][:]]
for start, end in intervals[1:]:
if start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
The solution carefully copies the first interval with intervals[0][:] because we later mutate merged[-1][1]. Without this copy, we would modify the caller's original data through the shallow copy made by sorted().