Inserting and merging a new interval into a set of intervals

Question

Given a sorted set of intervals (sorted based on the 1st value of a given range) that do not overlap, write a function to insert a new interval into the set of intervals. You can merge values in the sorted set to accommodate the new interval. Below are a few examples:

Example 1:
Set of intervals: [1, 2], [7, 10]
Insert: [2, 5]
New set of intervals: [1, 5], [7, 10]

Example 2:
Set of intervals: [1, 2], [4, 7], [8, 10], [12, 16]
Insert: [4, 9]
New set of intervals: [1, 2], [4, 10], [12, 16]

Example 3:
Set of intervals: [1, 2], [4, 7]
Insert: [4, 9]
New set of intervals: [1, 2], [4, 9]

Solution

Access restricted

Subscribe to premium account to see the solution.

Get premium now