Insert Interval - Problem
You are given an array of non-overlapping intervals intervals where intervals[i] = [start_i, end_i] represent the start and the end of the i-th interval and intervals is sorted in ascending order by start_i.
You are also given an interval newInterval = [start, end] that represents the start and end of another interval.
Insert newInterval into intervals such that intervals is still sorted in ascending order by start_i and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals after the insertion.
Input & Output
Example 1 — Basic Overlap
$
Input:
intervals = [[1,3],[6,9]], newInterval = [2,5]
›
Output:
[[1,5],[6,9]]
💡 Note:
newInterval [2,5] overlaps with [1,3], so we merge them to [1,5]. The interval [6,9] doesn't overlap, so it remains unchanged.
Example 2 — Multiple Overlaps
$
Input:
intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
›
Output:
[[1,2],[3,10],[12,16]]
💡 Note:
newInterval [4,8] overlaps with [3,5], [6,7], and [8,10], so we merge them all into [3,10]. Intervals [1,2] and [12,16] remain separate.
Example 3 — No Overlap
$
Input:
intervals = [[1,5]], newInterval = [6,8]
›
Output:
[[1,5],[6,8]]
💡 Note:
newInterval [6,8] doesn't overlap with [1,5] since 6 > 5, so we simply add it to the end.
Constraints
- 0 ≤ intervals.length ≤ 104
- intervals[i].length == 2
- 0 ≤ starti ≤ endi ≤ 105
- intervals is sorted by starti in ascending order
- newInterval.length == 2
- 0 ≤ start ≤ end ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Sorted non-overlapping intervals + new interval to insert
2
Process
Find overlaps and merge intervals while maintaining sorted order
3
Output
New sorted array with merged intervals
Key Takeaway
🎯 Key Insight: Process intervals in three phases - before, overlapping, and after the new interval
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code