Merge Intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Examples
Constraints
1 <= intervals.length <= 10^4intervals[i].length == 20 <= starti <= endi <= 10^4
Sort and Merge
Approach
First, we sort the intervals based on their start times. We initialize our result list and add the first interval to it. Then, we iterate through the remaining intervals. For each interval, we compare its start time with the end time of the last interval in our result list. If the current interval's start time is less than or equal to the last interval's end time, they overlap, so we merge them by updating the last interval's end time to `max(last.end, current.end)`. If they do not overlap, we simply add the current interval to the result list.
Complexity Analysis
Time complexity is O(n log n) due to the sorting step. The iteration takes O(n). Space complexity is O(n) to store the result (and sorting might take O(n) space depending on the language implementation).
class Solution { public int[][] merge(int[][] intervals) { if (intervals.length <= 1) { return intervals; } // Sort by starting time Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); List<int[]> res = new ArrayList<>(); int[] currentInterval = intervals[0]; res.add(currentInterval); for (int[] interval : intervals) { int currentEnd = currentInterval[1]; int nextBegin = interval[0]; int nextEnd = interval[1]; // Overlapping intervals if (currentEnd >= nextBegin) { currentInterval[1] = Math.max(currentEnd, nextEnd); } else { // Non-overlapping, add to result and update current currentInterval = interval; res.add(currentInterval); } } return res.toArray(new int[res.size()][]); }}