Problem overview
The method merge receives an int[][] named intervals, where each int[] holds a start and an end. It merges every group of overlapping intervals and returns the intervals that remain as an int[][], sorted by start. Two intervals overlap when they share at least one point, so [1,4] and [4,5], which share the point 4, merge into [1,5].
For [[1,3],[2,6],[8,10],[15,18]] the result is [[1, 6], [8, 10], [15, 18]]: the first two overlap and become [1,6], and the others overlap nothing. The input can be unsorted, as in [[6,8],[1,9],[2,4],[4,7]], which merges into the single interval [[1, 9]]. The statement asks for O(n log n) time.
Approach: sort, then sweep once
Checking every interval against every other costs O(n²), and merging can chain: [1,3] may join [2,6], and the result may then join [5,9]. Sorting by start makes the chain easy to follow. After sorting, any intervals that overlap sit next to each other, so one left-to-right pass is enough.
The pass keeps a list of merged intervals. For each interval, compare its start with the end of the last merged one:
- It starts after that end. It can't overlap anything so far, because the intervals arrive in order of start. It becomes a new merged interval.
- It starts at or before that end. It overlaps the last merged interval, so extend that one: its end becomes the larger of the two ends. Keeping the larger end matters when the new interval lies completely inside, like
[2,3]inside[1,10], where the end must stay 10.
The sort takes O(n log n) and the pass takes O(n), so the sort sets the total.
Step by step
- Sort
intervalsby start withArrays.sortand the comparator lambda(first, second) -> first[0] - second[0]. A negative result putsfirstbeforesecond. - Create
merged, aList<int[]>backed by a newArrayList. The number of merged intervals isn't known in advance, so it needs to grow. - Loop over every
int[] intervalwith a for-each loop. They arrive in order of start. - Name the two ends:
startisinterval[0]andendisinterval[1], so the next lines read like the idea. - Decide whether this starts a new merged interval. It does if
mergedis empty or the last merged interval ends beforestart. Use<, not<=: an interval that starts exactly where the last ends touches it, and touching intervals merge. In that case addnew int[]{start, end}. - Otherwise extend the last merged interval. Set its end to
Math.maxof its current end andend. - Return
merged.toArray(new int[0][]). It copies the list into a new array of arrays of exactly the right size.
The solution in Java
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (first, second) -> first[0] - second[0]);
List<int[]> merged = new ArrayList<>();
for (int[] interval : intervals) {
int start = interval[0], end = interval[1];
if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < start) {
merged.add(new int[]{start, end});
} else {
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], end);
}
}
return merged.toArray(new int[0][]);
}
}
Java details worth noticing:
- Imports.
Arrays,ListandArrayListall live injava.util. Outside the lesson's editor the file needsimport java.util.*;. List<int[]>. A generic list can holdint[]elements because arrays are objects, but it can't be aList<int>: generics take reference types, not primitives.- Changing an interval in place.
merged.get(merged.size() - 1)returns the actualint[]stored in the list, not a copy, so assigning to its element[1]changes the stored interval. toArray(new int[0][]). The empty array tells Java the element type,int[], and the method allocates an array of the right length. It returns anint[][], which is whatmergepromises.- What gets modified. Each merged interval is created with
new int[]{start, end}, and only these new arrays are ever extended, so the rows of the input are not changed by the merging. The sort does reorder the caller'sintervalsarray in place, so after the call the input is sorted by start. A caller who needs the original order must pass a copy. - Subtraction in the comparator is safe because starts stay within 0 to 1,000,000. For values near the limits of
intit can overflow, andInteger.compareis the safe choice.
Complexity
Time: O(n log n). Sorting is O(n log n). The loop touches each interval once, and ArrayList.add and get are constant time.
Space: O(n). In the worst case, when nothing overlaps, merged holds n intervals, and the sort uses some working space as well.
Edge cases and common mistakes
- Touching intervals.
[[1,4],[4,5]]returns[[1, 5]]. With<=in the check they would stay apart. - Unsorted input. Without the sort,
[[6,8],[1,9],[2,4],[4,7]]would be processed in the wrong order and miss the merges. With it, the result is[[1, 9]]. - An interval inside another.
[[1,10],[2,3]]returns[[1, 10]]. Setting the end toendinstead of the larger value would shrink it to 3. - A single interval.
[[5,5]]returns[[5, 5]]. A start equal to the end is allowed. - Merging into a copy. The in-place update works because
getreturns the stored array. Copying its values into new variables and changing those leaves the list unchanged.
Testing
[[1,3],[2,6],[8,10],[15,18]]gives[[1, 6], [8, 10], [15, 18]].[[1,4],[4,5]]gives[[1, 5]].[[6,8],[1,9],[2,4],[4,7]]gives[[1, 9]].[[1,10],[2,3]]gives[[1, 10]].[[5,5]]gives[[5, 5]].
