Question
You are given an array of non-overlapping intervals
intervalswhereintervals[i] = [starti, endi]represent the start and the end of theithinterval andintervalsis sorted in ascending order bystarti. You are also given an intervalnewInterval = [start, end]that represents the start and end of another interval.Insert
newIntervalintointervalssuch thatintervalsis still sorted in ascending order bystartiandintervalsstill does not have any overlapping intervals (merge overlapping intervals if necessary).Return
intervalsafter the insertion.Note that you don’t need to modify
intervalsin-place. You can make a new array and return it.
This is an intervals question.
Idea
- Iterate through the intervals
- We need to handle the following cases:
- No overlap before all intervals (new end value < current start value)
- No overlap after all intervals
- Append after all intervals
- No overlap between intervals
- Overlap with one interval
- Overlap with multiple intervals
- To handle these cases we really only need to check for three cases given a certain interval combination:
- The newInterval’s end is < intervals start
- Append newInterval then add all intervals to res
- Return res
- The newInterval’s start is > intervals end
- Append interval to res but newInterval could overlap with the next interval so continue to next interval
- Else case (overlap)
- Set newInterval to start at the min start points and end at the max end point then continue to next case to deal with another overlap, or the end of the interval case
- The newInterval’s end is < intervals start
- Theres one more edge case if we have an interval being completely absorbed or when interval is empty, then we never end up adding the newInterval to the result so we need to append newInterval to res outside the loop
- Return res