Consolidate Overlapping Time Ranges
Greedy & IntervalsAuto-graded · 18 test casesLast updated
Tests whether a candidate can sort and linearly sweep a list of ranges to produce the minimal set of non-overlapping intervals covering all input.
Problem Statement
You are given a list of ranges, where each element is a two-element list [start, end] representing a closed range from start to end (inclusive). Two ranges are considered overlapping if they share any point, including a single endpoint.
Your task is to collapse all overlapping ranges into a single range covering both, repeating until no two ranges in your result overlap. Return the final list of non-overlapping ranges in any order. Ranges that share exactly one endpoint must be merged (e.g., [1, 4] and [4, 7] become [1, 7]).
A range [a, b] is entirely contained within [c, d] when c <= a and b <= d. Contained ranges must be absorbed: the result should be the outer range, not two separate entries.
Constraints
1 <= len(ranges) <= 10^4- Each element of
rangeshas exactly 2 integers. 0 <= start <= end <= 10^4for every range.
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
If the ranges were sorted by their start value, what can you say about which ranges could possibly overlap with a given range?
Hint 2
Walk through the sorted list once, keeping track of the range you are currently building. When does the current range end, and when do you start a new one?
Hint 3
When extending the current range, is it always safe to take the new range's end as the updated boundary? Think about what happens when one range is completely inside another.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Insight
Two ranges can only overlap if no gap separates them. Once you sort all ranges by their start value, any range that overlaps the one you are currently building must appear immediately after it in the sorted order — it cannot "skip over" a gap. This turns an O(n²) pairwise-comparison problem into a single O(n) sweep.
Algorithm
- Sort the input by start value.
- Seed the output list with a copy of the first range.
- Sweep through the rest one range at a time:
- If the current range's start is less than or equal to the last output range's end, they overlap or touch. Extend the last output range's end to the maximum of the two ends.
- Otherwise there is a genuine gap. The last output range is complete; append the current range as a new entry.
- Return the output list.
Why Each Detail Matters
<= not < for the overlap check. The problem requires that ranges sharing a single endpoint be merged. Using strict less-than would incorrectly leave [1,4] and [4,5] as two separate entries instead of merging them into [1,5].
max on the end value. When one range is entirely contained inside another — e.g., [1,10] followed by [2,5] — the inner range's end is smaller than the current boundary. Blindly writing 5 as the new end would shrink the block incorrectly. Taking max(10, 5) = 10 preserves the full extent.
Copying the first range. The algorithm updates the last entry in the output list in place. Copying rather than referencing avoids mutating the caller's data, which is an easy-to-miss correctness issue.
Correctness Invariants
After processing each range in sorted order, two properties hold:
- Every entry in the output list except the last is final. Its end is strictly less than the start of all remaining ranges, so nothing can reach back and extend it.
- The last entry is exactly the union of a contiguous run of sorted ranges whose starts and ends have been correctly minimized and maximized.
Together these guarantee the output is disjoint, covers every input range, and is maximally merged.
Complexity
- Time: O(n log n) dominated by the sort; the sweep is O(n).
- Space: O(n) for the sorted copy and the output list, plus up to O(n) auxiliary space used internally by Python's Timsort.
Edge Cases
| Scenario | Behavior |
|---|---|
| Single range | Returned as-is; the loop body never executes. |
Contained range ([[1,10],[2,5]]) | max absorbs it; result is [[1,10]]. |
Touching endpoints ([[1,4],[4,5]]) | <= merges them; result is [[1,5]]. |
Zero-length range ([[3,3],[3,7]]) | Valid since start <= end; merges to [[3,7]]. |
| Unsorted or duplicate input | Sorting places overlapping ranges adjacent before the sweep begins. |
Reference Solution
from typing import List
def consolidate_ranges(ranges: List[List[int]]) -> List[List[int]]:
if not ranges:
return []
# Sort by start so that any overlapping ranges are guaranteed to be adjacent.
ordered = sorted(ranges, key=lambda r: r[0])
# Seed the result with a copy of the first range to avoid mutating the input.
result = [ordered[0][:]]
for start, end in ordered[1:]:
if start <= result[-1][1]:
# Overlaps or touches the current range: extend its end if needed.
result[-1][1] = max(result[-1][1], end)
else:
# Gap between ranges: the current range is final; open a new one.
result.append([start, end])
return result