Introduction
Insert Interval is a classic interval greedy problem.
You are given:
- A list of non-overlapping intervals sorted by start time
- A new interval
Goal:
Insert the new interval into the list and merge overlapping intervals if necessary.
Example
Input
intervals = [[1,3],[6,9]]newInterval = [2,5]
Output
[[1,5],[6,9]]Explanation
[2,5] overlaps with [1,3].
After merging:
[1,5]
Key Observation
The intervals are already sorted.
Only intervals overlapping with the new interval need merging.
Algorithm
- Add all intervals ending before newInterval starts.
- Merge all overlapping intervals.
- Add merged interval to answer.
- Add remaining intervals.
- Return result.
Dry Run
Input
intervals = [[1,3],[6,9]]newInterval = [2,5]First Interval
[1,3] overlaps with [2,5]Merge
start = min(1,2) = 1end = max(3,5) = 5
Merged Interval = [1,5]
Next Interval
[6,9]No OverlapAnswer
[[1,5],[6,9]]Approach : Greedy
Traverse intervals from left to right.
Merge all intervals that overlap with the new interval and keep all non-overlapping intervals unchanged.
Practice
Complexity Analysis
Time Complexity: O(n)Explanation: Each interval is processed at most once while traversing the array.
Space Complexity: O(n)
Explanation: The result array may store all intervals in the worst case.
Why This Problem is Important