Insert Interval
Fit a new range into a sorted list of disjoint ranges in one pass: copy, merge the overlaps, copy the rest.
The problem
You get a list of intervals that don't overlap and are sorted by start, plus one more interval, newInterval. Insert newInterval so that the list stays sorted and still has no overlaps, merging it with every interval it overlaps; intervals that only touch also count as overlapping. Return the new list.
Input intervals = [[1, 2], [4, 6], [8, 11], [13, 15]], newInterval = [5, 9]
Output [[1, 2], [4, 11], [13, 15]]
[5, 9] overlaps [4, 6] and [8, 11], so the three of them become [4, 11].
Input intervals = [[2, 3], [7, 8]], newInterval = [4, 5]
Output [[2, 3], [4, 5], [7, 8]]
Nothing overlaps, so the new interval simply slides into its sorted place.
Key constraint: The list is already sorted and its intervals don't overlap, so one linear pass is enough and no sorting is needed.
How to spot the pattern
- A sorted list of disjoint ranges, and one new range to fit in.
- The intervals the new one overlaps always form one unbroken stretch of the list.
The idea
Because the list is sorted and disjoint, it splits into three runs: intervals that end before the new one starts, intervals that overlap it, and intervals that start after it ends. Copy the first run unchanged, fold every overlapping interval into the new one by widening its start and end, add that merged interval, and copy the last run.
Brute force: Append the new interval and run the whole Merge Intervals algorithm, which sorts again and costs O(n log n) instead of O(n).
Step by step
- 1Copy every interval whose end is smaller than the start of
newInterval; they come before it untouched. - 2While the next interval starts at or before the end of
newInterval, widennewIntervalto the smaller start and the larger end of the two. - 3Add the widened
newIntervalto the result. - 4Copy all remaining intervals and return the result.
See the pattern move
The intervals pattern on a small example. Step through it, or press play.
Code
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
result = []
start, end = newInterval
i, n = 0, len(intervals)
# 1. Intervals that end before the new one starts.
while i < n and intervals[i][1] < start:
result.append(intervals[i])
i += 1
# 2. Intervals that overlap (or touch) the new one: fold them in.
while i < n and intervals[i][0] <= end:
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i += 1
result.append([start, end])
# 3. Intervals that start after it ends.
result.extend(intervals[i:])
return resultComplexity
Time
O(n)
Space
O(n)
Each interval is looked at once; the result holds up to n + 1 intervals.
Watch out for
- Using strict comparisons in the overlap check, which leaves touching intervals like [4, 6] and [6, 8] separate.
- Forgetting the cases where the new interval belongs at the very start or the very end of the list.
- Inserting into the input list while looping over it, which shifts the indexes and skips intervals.
Follow-up questions
Can you find the overlapping stretch faster than a linear scan?
Yes: binary search for the first interval that ends at or after the new start and the last one that starts at or before the new end. Building the output list is still O(n), but the search is O(log n).
What if many new intervals have to be inserted?
Add them all and run Merge Intervals once, for O(n log n). If they arrive one at a time, keep the intervals in a balanced tree keyed by start so each insert costs O(log n) plus the intervals it merges.
In Hinglish
Teen hisse socho: jo pehle hi khatam ho gaye, jo naye interval se overlap karte hain, aur jo baad mein shuru hote hain. Beech wale sab ko ek interval mein mila do.