Merge all overlapping intervals and return the simplified non-overlapping intervals.
Problem Statement
Examples
Input: intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Output: [[1, 6], [8, 10], [15, 18]]
Explanation: Since intervals [1, 3] and [2, 6] overlap, merge them into [1, 6].
Input: intervals = [[1, 4], [4, 5]]
Output: [[1, 5]]
Explanation: Combining the input according to Merge Overlapping Subintervals logic yields [[1, 5]].
Complexity
Time Complexity: O(N log N)
Space Complexity: O(N)
Hints
Editorial & Approach
Problem Overview & Intuition
By sorting intervals by their start coordinate, any overlapping intervals will appear consecutively. Comparing the current interval start with the previous interval end resolves all merges in a single linear pass.
Step-by-Step Approach
- Sort
intervalsby starting valuea[0] - b[0]. - Initialize
result = [intervals[0]]. - Iterate from
i = 1tointervals.length - 1. - If
intervals[i][0] <= last[1]: merge bylast[1] = Math.max(last[1], intervals[i][1]). - Otherwise, push
intervals[i]toresult. - Return
result.
Optimal Implementation (JavaScript)
function mergeIntervals(intervals) {
if (!intervals.length) return [];
intervals.sort((a, b) => a[0] - b[0]);
const result = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const current = intervals[i];
const last = result[result.length - 1];
if (current[0] <= last[1]) {
last[1] = Math.max(last[1], current[1]);
} else {
result.push(current);
}
}
return result;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Single interval: returns [interval].
- Adjacent touching intervals [1, 4] and [4, 5]: merge to [1, 5].
- One interval completely containing another [1, 10] and [2, 6].