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. Return intervals
after the insertion.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Example 3:
Input: intervals = [], newInterval = [5,7]
Output: [[5,7]]
Example 4:
Input: intervals = [[1,5]], newInterval = [2,3]
Output: [[1,5]]
Example 5:
Input: intervals = [[1,5]], newInterval = [2,7]
Output: [[1,7]]
intervals
is empty or the new interval does not overlap with any current interval.Here’s the implementation of the above strategy:
def insert(intervals, newInterval):
result = []
i = 0
n = len(intervals)
# Add intervals before the new interval
while i < n and intervals[i][1] < newInterval[0]:
result.append(intervals[i])
i += 1
# Merge overlapping intervals with new interval
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
result.append(newInterval)
# Add remaining intervals after new interval
while i < n:
result.append(intervals[i])
i += 1
return result
O(n)
, where n
is the number of intervals.O(n)
as we are storing the resulting intervals, which may be equal to the input size in the worst case.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?