Merge Intervals - Problem
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.
Two intervals overlap if they share at least one common point. For example, [1,3] and [2,6] overlap because they share the range [2,3].
Example: If you have intervals [[1,3],[2,6],[8,10],[15,18]], the first two intervals overlap and should be merged into [1,6], resulting in [[1,6],[8,10],[15,18]].
Input & Output
Example 1 — Basic Overlapping Intervals
$
Input:
intervals = [[1,3],[2,6],[8,10],[15,18]]
›
Output:
[[1,6],[8,10],[15,18]]
💡 Note:
Intervals [1,3] and [2,6] overlap (share range [2,3]), so merge them into [1,6]. The other intervals [8,10] and [15,18] don't overlap with anything.
Example 2 — All Intervals Merge
$
Input:
intervals = [[1,4],[4,5]]
›
Output:
[[1,5]]
💡 Note:
Intervals [1,4] and [4,5] overlap at point 4, so they merge into [1,5].
Example 3 — No Overlaps
$
Input:
intervals = [[1,2],[3,4],[5,6]]
›
Output:
[[1,2],[3,4],[5,6]]
💡 Note:
No intervals overlap, so the result is the same as input.
Constraints
- 1 ≤ intervals.length ≤ 104
- intervals[i].length == 2
- 0 ≤ starti ≤ endi ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of intervals with some overlapping
2
Identify Overlaps
Find intervals that share common points
3
Merge
Combine overlapping intervals into single intervals
Key Takeaway
🎯 Key Insight: Sorting by start time transforms the problem into a simple linear scan for overlaps
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code