Question
You are given an array of non-overlapping intervalsÂ
intervals
 whereÂintervals[i] = [starti, endi]
 represent the start and the end of theÂith
 interval andÂintervals
 is sorted in ascending order byÂstarti
. 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Âstarti
 andÂintervals
 still does not have any overlapping intervals (merge overlapping intervals if necessary).ReturnÂ
intervals
 after the insertion.Note that you don’t need to modifyÂ
intervals
 in-place. You can make a new array and return it.
This is anintervals 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