Consolidate Overlapping Time Intervals
Greedy & IntervalsAuto-graded · 21 test casesLast updated
Evaluate ability to sort and combine overlapping or adjacent half-open numerical intervals in linear-arithmetic time.
Given a list of half-open intervals represented as pairs [start, end], combine all intervals that overlap or touch each other into a minimum set of disjoint intervals.
Two intervals [a, b] and [c, d] are considered touching if b == c or d == a. Zero-length intervals (where start == end) carry no length; if a zero-length interval falls within or touches another interval, it should be subsumed into the larger interval. If isolated, a zero-length interval [a, a] merges into itself or adjacent ranges as applicable.
The output list of merged intervals must be sorted by start time in ascending order.
Constraints
- $0 \le \text{len}(intervals) \le 10^5$
- Each interval is a list of two integers
[start, end]where $\text{start} \le \text{end}$. - Interval endpoints are integers in the range $[-10^9, 10^9]$.
Examples
Example 1
Input: merge_intervals([[1, 3], [2, 6], [8, 10], [10, 12]])
Output: [[1, 6], [8, 12]]
Example 2
Input: merge_intervals([[1, 2], [3, 4]])
Output: [[1, 2], [3, 4]]
Example 3
Input: merge_intervals([[5, 5], [1, 3], [3, 3], [3, 6]])
Output: [[1, 6]]
Hints
Hint 1
Sorting the input list by the initial endpoint simplifies the overlap check significantly.
Hint 2
Once sorted, you only need to compare the current interval's start time with the end time of the most recently processed interval in your output list.
Hint 3
Because adjacent/touching intervals (where interval A's end equals interval B's start) must be combined, check for `start <= previous_end` rather than strict inequality.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To merge overlapping or adjacent intervals, we can use a greedy sorting approach:
- Sort the Intervals: First, sort the list of intervals by their
startvalues (and byendvalues in case of ties). Sorting ensures that as we iterate through the list, any interval that could potentially overlap or touch an existing combined range will appear immediately next in line. - Linear Sweep & Combine: Maintain an output list
merged. Iterate through each interval[start, end]:- If
mergedis empty, or ifstart > merged[-1][1](the current interval starts after the last merged interval ends), there is no overlap or adjacency. Append[start, end]as a new interval tomerged. - Otherwise, the current interval overlaps or touches the previous range (
start <= merged[-1][1]). Expand the end boundary of the last interval inmergedtomax(merged[-1][1], end).
- If
Handling zero-length intervals [x, x] and touching boundaries [a, b] and [b, c] is natively managed by using the non-strict inequality check start <= merged[-1][1].
Complexity Analysis
- Time Complexity: $\mathcal{O}(n \log n)$, where $n$ is the number of intervals. Sorting the array takes $\mathcal{O}(n \log n)$ time, followed by a single linear pass taking $\mathcal{O}(n)$ time.
- Space Complexity: $\mathcal{O}(n)$ auxiliary space to store the merged result (or $\mathcal{O}(\log n)$ auxiliary space for Timsort if sorting in place).
from typing import List
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
# Sort by start time, then by end time
intervals.sort()
merged = []
for start, end in intervals:
# If output is empty or current interval doesn't touch/overlap the last output interval
if not merged or start > merged[-1][1]:
merged.append([start, end])
else:
# Overlapping or touching: extend the end of the last interval
merged[-1][1] = max(merged[-1][1], end)
return merged