Merge Intervals
Merge overlapping closed intervals. Intervals that share an endpoint also overlap.
Work through the cases
3 examplesInput notation
One start end interval per line, with start <= end.Expected result
Merged intervals ordered by start, one pair per line.Case 1
Input
1 4 3 6 8 9
Expected output
1 6 8 9
Case 2
Input
1 2 2 3
Expected output
1 3
Case 3
Input
-3 -1 -2 0
Expected output
-3 0
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
The first idea is to pick an interval and scan the rest for overlaps, merging until nothing changes. Correct, but worst-case O(n^2) with a messy merge order. n ≤ 10^4 is tight. The waste is locating overlaps in unsorted input. After sorting by left endpoint, an interval can overlap only the interval we have not closed yet—later starts are larger, so they cannot skip over the middle and overlap again. So we sort, then scan once, keeping st, ed as the interval under merge.
We can sort the intervals in ascending order by the left endpoint, and then traverse the intervals for merging operations.
The specific merging operation is as follows.
First, we add the first interval to the answer. Then, we consider each subsequent interval in turn:
- If the right endpoint of the last interval in the answer array is less than the left endpoint of the current interval, it means that the two intervals will not overlap, so we can directly add the current interval to the end of the answer array; - Otherwise, it means that the two intervals overlap. We need to use the right endpoint of the current interval to update the right endpoint of the last interval in the answer array, setting it to the larger of the two.
Finally, we return the answer array.
The time complexity is O(n × log n), and the space complexity is O(log n). Here, n is the number of intervals.
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
int st = intervals[0][0], ed = intervals[0][1];
List<int[]> ans = new ArrayList<>();
for (int i = 1; i < intervals.length; ++i) {
int s = intervals[i][0], e = intervals[i][1];
if (ed < s) {
ans.add(new int[] {st, ed});
st = s;
ed = e;
} else {
ed = Math.max(ed, e);
}
}
ans.add(new int[] {st, ed});
return ans.toArray(new int[ans.size()][]);
}
}Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.
Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.