3.10 Merge Intervals
3.10.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 56
- Difficulty: Medium
- URL: https://leetcode.com/problems/lc-merge-intervals/
- Tags: Grind 75, Blind 75, NeetCode 150
- Techniques: Sorting, Array
3.10.2 Description
Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return the result in ascending order of start time.
3.10.4 Constraints
1 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i <= end_i <= 10^4
3.10.5 Solution - Sort then Merge
3.10.5.1 Walkthrough
Sort the intervals by starting point. Iterate through them, merging with the last interval in the output when an overlap occurs (current.start <= last.end), otherwise append the new interval.
3.10.5.3 Implementation Steps
- Sort intervals ascending by start.
- Initialize an empty lc-list
merged. - For each interval:
- If
mergedis empty orcurrent.start > merged.last.end, append interval. - Else set
merged.last.end = max(merged.last.end, current.end).
- If
- Return
mergedas an array.
3.10.5.4 Code - Java
public int[][] merge(int[][] intervals) {
if (intervals.length == 0) {
return new int[0][0];
}
Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
List<int[]> merged = new ArrayList<>();
merged.add(intervals[0].clone());
for (int i = 1; i < intervals.length; i++) {
int[] current = intervals[i];
int[] last = merged.get(merged.size() - 1);
if (current[0] <= last[1]) {
last[1] = Math.max(last[1], current[1]);
} else {
merged.add(current.clone());
}
}
return merged.toArray(new int[merged.size()][]);
}