Consolidate Overlapping Ranges
Greedy & IntervalsAuto-graded · 18 test casesLast updated
Tests interval merging with sorting, overlapping logic, and immutability constraints
You are given a collection of closed ranges, where each range is represented as a pair [start, end] with start <= end. Your task is to combine all ranges that overlap or meet at their boundaries into a minimal set of non-overlapping ranges.
Two ranges are considered mergeable if one ends exactly where the other begins, or if they share any common values. For example, [3, 7] and [7, 10] should merge into [3, 10] because they meet at boundary point 7. However, [3, 5] and [6, 8] remain separate because no value belongs to both ranges.
Write a function that consolidates the input ranges and returns the minimal list of merged ranges.
Requirements:
- The output must be sorted by starting position
- Do not modify the input list or any of its elements
- Empty input should produce empty output
- Handle ranges in any order, including duplicates and single-point ranges (where start equals end)
- Support negative values
Constraints:
0 <= len(intervals) <= 100000- Each range contains exactly two integers
-10^9 <= start <= end <= 10^9
Examples
Example 1
Input: consolidate_ranges([[1, 3], [2, 6], [8, 10], [10, 12]])
Output: [[1, 6], [8, 12]]
Example 2
Input: consolidate_ranges([[5, 7], [1, 2], [2, 4], [9, 9]])
Output: [[1, 4], [5, 7], [9, 9]]
Hints
Hint 1
Start by organizing the ranges in a consistent order - what property makes sense to sort by?
Hint 2
Once sorted, can you process ranges in a single pass while tracking the current merged range?
Hint 3
When does a new range extend the current block versus starting a completely new block? Pay attention to the boundary-touching rule.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core strategy is to sort the ranges by their starting positions, then sweep through them once while maintaining a "current active range" that accumulates all mergeable ranges encountered so far.
After sorting, any range that can merge with the current active range must appear immediately next in the sequence - there's no need to look backwards. For each subsequent range [s, e]:
- If
s <= current_end, the new range either overlaps or touches the active range at its boundary. Extend the active range by settingcurrent_end = max(current_end, e). - If
s > current_end, there's a gap between ranges. Finalize the current active range and begin a new one starting at[s, e].
The <= comparison handles the boundary-touching requirement: [3, 7] and [7, 10] merge because 7 <= 7. Note that [3, 5] and [6, 8] do not merge since there's a genuine gap.
The max operation is critical for handling containment cases. When processing [[1, 10], [2, 5]] after sorting, the second range is completely contained within the first. Simply assigning e to the endpoint would incorrectly shrink the range.
Why It Works
After processing the first k sorted ranges, the output contains the minimal set of disjoint, non-touching ranges that cover exactly the union of those k ranges. Only the last range in the output can possibly merge with future input ranges.
When we encounter a new range [s, e] and find s > last_end, we know:
- Every previous range ends at or before
last_end - The gap from
last_endtosis uncovered by any input range - All future ranges start at positions
>= s(due to sorting) - Therefore, no future range can merge with any earlier finalized range
This guarantees that once we close a range and start a new one, the closed range never needs revisiting.
Complexity
Time: O(n log n) dominated by sorting, plus O(n) for the single linear pass through the sorted ranges.
Space: O(n) for the sorted copy and the output list. Python's sort also uses O(n) auxiliary space.
Implementation
from typing import List
def consolidate_ranges(intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
ordered = sorted((interval[0], interval[1]) for interval in intervals)
merged = [[ordered[0][0], ordered[0][1]]]
for start, end in ordered[1:]:
if start <= merged[-1][1]:
if end > merged[-1][1]:
merged[-1][1] = end
else:
merged.append([start, end])
return merged