Introduction
Merge Intervals is one of the most important interval problems.
You are given:
- A collection of intervals
Goal:
Merge all overlapping intervals and return the resulting intervals.
Example
Input
intervals = [[1,3],[2,6],[8,10],[15,18]]Output
[[1,6],[8,10],[15,18]]
Explanation
[1,3] and [2,6] overlap.
They are merged into [1,6].
Key Observation
If intervals are sorted by start time, overlapping intervals will appear next to each other.
Algorithm
- Sort intervals by start value.
- Add first interval to answer.
- Iterate through remaining intervals.
- If current interval overlaps:
- Merge intervals.
- Otherwise:
- Add new interval.
- Return result.
Dry Run
Input
[[1,3],[2,6],[8,10],[15,18]]
Sort
[[1,3],[2,6],[8,10],[15,18]]
Compare
[1,3] and [2,6]
Overlap Found
Merge
[1,6]
Next Interval
[8,10]
No Overlap
Next Interval
[15,18]
No Overlap
Answer
[[1,6],[8,10],[15,18]]
Approach : Greedy + Sorting
Sort intervals by start value.
If the current interval overlaps with the last merged interval, extend the end point.
Otherwise create a new interval.