Insert the specified interval into a collection of non-overlapping intervals that has been organized by the start time of each interval. If the new interval causes intervals to overlap, merge the overlapped intervals.

For example,

Input:
intervals = [(1, 5), (7, 8), (9, 10), (12, 15)]
interval = (5, 9)
Output: [(1, 10), (12, 15)]
Explanation: The interval (5, 9) overlaps with (1, 5), (7, 8), (9, 10)
 
Input:
intervals = [(2, 5), (7, 9)]
interval = (3, 4)
Output: [(2, 5), (7, 9)]
Explanation: The interval (3, 4) overlaps with (2, 5)

The idea is very simple: add an interval to the result if it does not overlap the given interval; otherwise, combine all overlapped intervals into one and push the resulting interval to the result. The implementation can be seen below in C++, Java, and Python.

C++


Download  Run Code

Output:

{1, 10}
{12, 15}

Java


Download  Run Code

Output:

[(1, 10), (12, 15)]

Python


Download  Run Code

Output:

[(1, 10), (12, 15)]

 
We can do the merging in-place without using any other data structure. The idea is to iterate through the intervals and merge the intervals that overlap with the designated interval, removing the intervals that have already been merged in the process. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

{1, 10}
{12, 15}

Java


Download  Run Code

Output:

[(1, 10), (12, 15)]

Python


Download  Run Code

Output:

[(1, 10), (12, 15)]

The time complexity of the above solution is O(n), where n is the total number of intervals.