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
  • 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

Solution