Consolidate Overlapping Time Ranges
Greedy & IntervalsAuto-graded · 18 test casesLast updated
Tests whether a candidate can sort and scan a list of closed intervals to collapse all overlapping or touching ranges into a minimal merged set.
Problem
You are given a collection of closed intervals, where each interval is represented as a two-element list [start, end] with start <= end. Two intervals should be joined together whenever they overlap or share an endpoint.
Your task is to collapse the collection into the smallest possible set of non-overlapping intervals that covers exactly the same set of points as the original input. Return the result sorted by the left endpoint of each interval.
Definitions
- A closed interval
[a, b]contains every integer pointxwitha <= x <= b. - Two intervals overlap if they share at least one point. This includes the case where one interval ends exactly where the next one begins (e.g.,
[1, 3]and[3, 5]share the point3). - One interval is nested inside another if every point it covers is already covered by the other (e.g.,
[2, 4]is nested inside[1, 7]).
What to return
A list of intervals [start, end], sorted by start, such that:
- No two intervals in the output overlap or touch.
- Every point covered by at least one input interval is covered by exactly one output interval.
Constraints
0 <= len(intervals) <= 10^4-10^5 <= start <= end <= 10^5for every interval- The input list may arrive in any order and may contain duplicate intervals.
- Do not modify the input list or its sublists.
Examples
Example 1
Input: merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])
Output: [[1, 6], [8, 10], [15, 18]]
Example 2
Input: merge_intervals([[1, 4], [4, 5]])
Output: [[1, 5]]
Hints
Hint 1
Try sorting the intervals by their left endpoint first — after sorting, any interval that can possibly overlap the current group must appear immediately after it, so a single left-to-right scan is enough.
Hint 2
As you scan, keep track of only the last merged interval. If the next interval's start is within (or touching) that interval's end, extend the end to whichever value is larger. Otherwise, the current group is complete — save it and start a new one.
Hint 3
Watch out for nested intervals like [1, 10] followed by [2, 3]: taking the new end naively would shrink your interval, so always take the maximum of the two ends when merging.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight
After sorting intervals by their left endpoint, any interval that could possibly overlap the current merged group must appear immediately to its right in the sorted order. This means a single left-to-right scan is sufficient — there is never a reason to look back more than one step.
Algorithm
- Handle the empty case. If the input is empty, return
[]. - Sort by left endpoint. Use Python's built-in sort on
intervals(viasortedto avoid mutating the input). This costs O(n log n). - Initialize with the first interval. Copy its values into a new list
merged. - Scan left to right. For each subsequent interval
[start, end]:- If
start <= merged[-1][1], the interval overlaps or touches the current group. Extend the group's right endpoint tomax(merged[-1][1], end). Themaxis necessary because the new interval might be fully nested inside the current group. - Otherwise, there is a true gap between the current group and this interval. Push a fresh entry
[start, end]ontomerged.
- If
- Return
merged. It is already sorted by left endpoint because the input was sorted and each new entry's start is strictly greater than the previous entry's end.
Why the comparison is <= and not <
The intervals are closed, so [1, 3] and [3, 5] share the point 3. Using strict less-than would incorrectly leave a gap at that shared point.
Correctness argument
- After sorting, the last block in
mergedalways holds the rightmost endpoint seen so far within that group, because of themaxupdate. - If the next interval's start falls past that endpoint, no later interval (whose start is at least as large) can overlap the current block either, so the block is finalized.
- If the next interval's start falls within the block, merging is required; expanding to the larger endpoint keeps the block exact.
Edge cases
| Situation | Example input | Expected output |
|---|---|---|
| Empty input | [] | [] |
| Single interval | [[3, 7]] | [[3, 7]] |
| Touching endpoints | [[1, 2], [2, 3]] | [[1, 3]] |
| Nested interval | [[1, 10], [2, 4]] | [[1, 10]] |
| Duplicate intervals | [[1, 2], [1, 2]] | [[1, 2]] |
| Negative values | [[-5, -1], [-3, 2]] | [[-5, 2]] |
| Already disjoint | [[1, 2], [4, 5]] | [[1, 2], [4, 5]] |
Complexity
- Time: O(n log n) dominated by the sort; the scan is O(n).
- Space: O(n) for the sorted copy and the output list. The input is never mutated.
Reference solution
from typing import List
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
ordered = sorted(intervals, key=lambda interval: interval[0])
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