Problem
Given a list of intervals, merge every overlapping pair and return the resulting disjoint intervals in order.
Original: LeetCode 56: Merge Intervals.
Examples
Example 1
`intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]``[[1, 6], [8, 10], [15, 18]]`Example 2
`intervals = [[1, 4], [4, 5]]``[[1, 5]]`Touching intervals count as overlapping.
Constraints
1 <= intervals.length <= 10^4intervals[i].length == 20 <= starti <= endi <= 10^4
Hints
Hint 1
Closed intervals that only touch at an endpoint also merge, because the start of one equals the end of the other.
Hint 2
Interval merging: sort by start, then a linear scan that extends the running end.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Repeatedly search for any overlapping pair and merge them, which can be quadratic.
Optimal. Sort by start, then one pass.
Alternative. A sweep line with +1 at starts and -1 at ends also works, but it is more machinery than you need for this problem.
Complexity
- Time
- O(n log n)
O(n log n) time for the sort, then O(n) for the merge. O(n) space for the output.
- Space
- O(n)
Code
def merge(intervals: list[list[int]]) -> list[list[int]]:
intervals = sorted(intervals)
out = [intervals[0][:]]
for start, end in intervals[1:]:
if start <= out[-1][1]:
out[-1][1] = max(out[-1][1], end)
else:
out.append([start, end])
return out
if __name__ == "__main__":
assert merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
assert merge([[1, 4], [4, 5]]) == [[1, 5]]
print("ok")import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MergeIntervals {
static int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> out = new ArrayList<>();
int[] cur = intervals[0];
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] <= cur[1]) {
cur[1] = Math.max(cur[1], intervals[i][1]);
} else {
out.add(cur);
cur = intervals[i];
}
}
out.add(cur);
return out.toArray(new int[0][]);
}
public static void main(String[] args) {
int[][] a = merge(new int[][] {{1, 3}, {2, 6}, {8, 10}, {15, 18}});
if (!Arrays.deepEquals(a, new int[][] {{1, 6}, {8, 10}, {15, 18}})) throw new AssertionError(Arrays.deepToString(a));
int[][] b = merge(new int[][] {{1, 4}, {4, 5}});
if (!Arrays.deepEquals(b, new int[][] {{1, 5}})) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: [[1,3],[2,6],[8,10],[15,18]] becomes [[1,6],[8,10],[15,18]], and [[1,4],[4,5]] becomes [[1,5]].
- An interval completely inside another only extends the end if the inner end is larger, which the max handles.
Follow-ups
- Insert Interval is this problem with one new interval and an already-sorted list.
- Meeting Rooms asks whether any two overlap, which is the same sort without merging.
Interview script
"I sort by start time so any overlap has to be with the interval I am already holding. I extend the current end when the next start is not to the right of it, otherwise I emit the current interval and start a new one."
Source: LeetCode 56: Merge Intervals
Sources (1)
- LeetCode 56: Merge Intervalsleetcode.com