Merge overlapping closed intervals with a sort-and-scan algorithm. See how Java and Python handle touching endpoints, nesting, and empty input.
Problem and input contract
Given pairs (start, end) with start ≤ end, return sorted, disjoint closed intervals with the same union. The functions preserve the input.
[(5, 7), (1, 3), (3, 6)] gives [(1, 7)]. [(1, 9), (2, 4), (12, 12)] gives [(1, 9), (12, 12)]. Empty input gives an empty result.
Worked example
[(5, 7), (1, 3), (3, 6)] merges to [(1, 7)].
After sorting, process (1, 3) first. The next interval starts at 3, so it touches the first and extends it to (1, 6). The last interval starts at 5 and extends the end to 7.
How the solution works
Sorting by start means the last merged interval is the only candidate for overlap with the next input interval. Using max preserves the existing end when the new interval is contained.
These are closed intervals, so equality counts as overlap. Sorting by start means a gap closes off all earlier merged intervals. The Java implementation copies arrays before modifying them.
Python solution
def merge_intervals(intervals):
merged = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]:
previous_start, previous_end = merged[-1]
merged[-1] = (previous_start, max(previous_end, end))
else:
merged.append((start, end))
return mergedJava solution
import java.util.*;
class Solution {
static List<int[]> mergeIntervals(int[][] intervals) {
int[][] sorted = intervals.clone();
Arrays.sort(sorted, Comparator.comparingInt(pair -> pair[0]));
List<int[]> merged = new ArrayList<>();
for (int[] pair : sorted) {
int[] last = merged.isEmpty() ? null : merged.get(merged.size() - 1);
if (last != null && pair[0] <= last[1]) {
last[1] = Math.max(last[1], pair[1]);
} else {
merged.add(pair.clone());
}
}
return merged;
}
}Approaches and complexity
Checking every pair for overlap can take quadratic work before accounting for repeated merges. Sorting the starts brings intervals that can contribute to the same output segment together. Sorting takes O(n log n) worst-case time and the scan takes O(n). The sorted copy and sort workspace use O(n) auxiliary space, plus the output. With already sorted input, the scan alone is linear.
| Approach | Time | Auxiliary space | Advantage | Limitation | Use case |
|---|---|---|---|---|---|
| Sort and scan | O(n log n) | O(n) | Handles unsorted input | Needs sorting | General input |
| Scan sorted intervals | O(n) | O(1) excluding output | Linear traversal | Requires sorted starts | Input already sorted |
Common mistakes and interview follow-up
Use start ≤ lastEnd for closed intervals. Keep the larger endpoint so a nested interval cannot shrink the union. Once the next start exceeds the current end, all later starts lie beyond that end.
Related practice: Find the First Occurrence with Binary Search.
Comments
Post a Comment