Insert Interval

Problem

Given a list of intervals intervals and an interval newInterval, write a function to insert newInterval into a list of existing, non-overlapping, and sorted intervals based on their starting points. The function should ensure that after the new interval is added, the list remains sorted without any overlapping intervals, merging them if needed.

Two intervals are considered overlapping if they share any common time, including if one ends exactly when another begins (e.g., [1,4] and [4,7] overlap and should be merged into [1,7]).

Input:

intervals = [[1,3],[6,9]]
newInterval = [2,5]

Output:

[[1,5],[6,9]]

Explanation: The new interval [2,5] overlaps with [1,3], so they are merged into [1,5].

Input:

intervals = [[1,2],[3,5],[6,7],[8,10]]
newInterval = [5,6]

Output:

[[1,2],[3,7],[8,10]]

Explanation: The new interval [5,6] touches [3,5] and [6,7], so all three are merged into [3,7].

Explanation

We first want to create a new list merged to store the merged intervals we will return at the end.

This solution operates in 3 phases:

  • Add all the intervals ending before newInterval starts to merged.
  • Merge all overlapping intervals with newInterval and add that merged interval to merged.
  • Add all the intervals starting after newInterval to merged.
Phase 1

In this phase, we add all the intervals that end before newInterval starts to merged. This involves iterating through the intervals list until the current interval no longer ends before newInterval starts (i.e. intervals[i][1] >= newInterval[0]).

Phase 2

In this phase, we merge all the intervals that overlap with newInterval together into a single interval by updating newInterval to be the minimum start and maximum end of all the overlapping intervals. This includes intervals that merely “touch” newInterval (e.g. [1,4] and [4,7] should merge into [1,7]). We iterate through the intervals list until the current interval starts after newInterval ends (i.e. intervals[i][0] > newInterval[1]). When that condition is met, we add newInterval to merged and move onto phase 3.

Phase 3

Phase 3 involves adding all the intervals starting after newInterval to merged. This involves iterating through the intervals list until the end of the list, and adding each interval to merged.

After completing these 3 phases, we return merged as the final result.

Solution