Home
DSA Patterns
Intervals
Insert Interval
Problem Understanding
You are given an array of non-overlapping intervals sorted by start time. Your task is to insert a new interval into this list and merge any necessary intervals to maintain the sorted, non-overlapping property.
Example:
- Input:
intervals = [[1,3],[6,9]],newInterval = [2,5] - Output:
[[1,5],[6,9]] - Why?
[2,5]overlaps with[1,3]. Combining them gives[1,5].
Algorithm Strategy
Since the list is already sorted, we can solve this in O(N) time using a single pass with three phases:
- Skip Left: Add all intervals that come strictly before the new interval (where
end < newStart). - Merge Overlaps: Use a
whileloop to process intervals that overlap with the new one (wherestart <= newEnd). Continuously update the new interval to[min(start), max(end)]. - Append Right: Once overlaps are resolved, add the (possibly expanded) new interval, then add all remaining intervals.
Interactive Visualization
Visualize the three-phase linear scan strategy.
Dry Run
Input: [[1,3], [6,9]], New: [2,5]
| Step | Interval | Overlap? | Action | Result |
|---|---|---|---|---|
| 1 | [1,3] |
Yes (1 <= 5) |
Merge! New is [1, 5] |
[] |
| 2 | [6,9] |
No (6 > 5) |
Stop merging. Add New [1,5]. Add Curr [6,9] |
[[1,5], [6,9]] |
| Final | - | - | - | [[1,5], [6,9]] |
Edge Cases & Common Mistakes
- New Interval is First/Last: e.g., Inserting
[0,1]or[10,12]into[[2,5]]. - No Overlaps: New interval fits perfectly in a gap.
- Complete Overlap: New interval covers multiple existing ones
[1,10]covers[2,3], [4,5].
Solution
Linear scan implementation.
Insert Interval Code
1var insert = function(intervals, newInterval) {2 const result = [];3 let i = 0;4 const n = intervals.length;56 // 1. Left7 while (i < n && intervals[i][1] < newInterval[0]) {8 result.push(intervals[i++]);9 }1011 // 2. Merge12 while (i < n && intervals[i][0] <= newInterval[1]) {13 newInterval[0] = Math.min(newInterval[0], intervals[i][0]);14 newInterval[1] = Math.max(newInterval[1], intervals[i][1]);15 i++;16 }17 result.push(newInterval);1819 // 3. Right20 while (i < n) {21 result.push(intervals[i++]);22 }2324 return result;25};
