Introduction
The Merge Intervals problem involves combining overlapping intervals into a single interval.
Given:
- an array of intervals
the task is to:
- merge all overlapping intervals
- return non-overlapping merged intervals
This problem is one of the most important applications of:
Sorting + Interval ProcessingThis problem helps in understanding:
- interval merging
- sorting
- greedy traversal
- overlapping ranges
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 and merge into:
[1,6]
Constraints
1 <= intervals.length <= 10^50 <= start <= end <= 10^5Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Compare every interval
with remaining intervals - Merge overlapping intervals
- Repeat until no overlaps remain
This approach works but repeated comparisons increase complexity.
Steps
- Sort intervals.
- Compare intervals repeatedly.
- Merge overlaps.
- Continue traversal.
- Return merged intervals.
Dry Run
Input:[[1,3],[2,6],[8,10],[15,18]]
Compare:
[1,3] and [2,6]
Overlap exists
Merge:
[1,6]
Remaining intervals:
[[1,6],[8,10],[15,18]]
No further overlaps
Final Result:
[[1,6],[8,10],[15,18]]
Brute Force Code
Complexity Analysis
Time Complexity: O(n log n)Explanation:
Sorting dominates the complexity.
Space Complexity: O(n)
Explanation:
Extra merged array is used.
Approach 2 : Optimized Interval Merging
Explanation
The optimized solution uses:
Sorting + Greedy Traversal
The idea is:
- Sort intervals by start time
- Compare with last merged interval
- Merge if overlap exists
- Otherwise add new interval
This avoids repeated comparisons.
The optimized solution uses:
Sorting + Greedy TraversalThe idea is:
- Sort intervals by start time
- Compare with last merged interval
- Merge if overlap exists
- Otherwise add new interval
This avoids repeated comparisons.
Steps
- Sort intervals.
- Add first interval.
- Traverse remaining intervals.
- Merge overlaps.
- Add non-overlapping intervals.
- Return merged result.
- Sort intervals.
- Add first interval.
- Traverse remaining intervals.
- Merge overlaps.
- Add non-overlapping intervals.
- Return merged result.
Dry Run
Input:[[1,3],[2,6],[8,10],[15,18]]
Sorted intervals:
[[1,3],[2,6],[8,10],[15,18]]
Start with:
[1,3]
Compare with:
[2,6]
Overlap exists
Merge:
[1,6]
Compare with:
[8,10]
No overlap
Add interval
Final Result:
[[1,6],[8,10],[15,18]]
Optimized Interval Merging Code
Complexity Analysis
Time Complexity: O(n log n)Explanation:
Sorting dominates the complexity.
Space Complexity: O(n)
Explanation:
Merged intervals are stored separately.
Edge Cases