{x}
blog image

Insert Interval

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.

 

Example 1:

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

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

 

Constraints:

  • 0 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 105
  • intervals is sorted by starti in ascending order.
  • newInterval.length == 2
  • 0 <= start <= end <= 105

Solution Explanation for Insert Interval

This problem involves inserting a new interval into a sorted list of non-overlapping intervals and merging overlapping intervals. Two approaches are presented below:

Approach 1: Sorting and Merging

This approach involves three steps:

  1. Append: Add the newInterval to the intervals array.
  2. Sort: Sort the combined array intervals based on the start time of each interval.
  3. Merge: Iterate through the sorted array and merge overlapping intervals. This involves comparing the end time of the current interval with the start time of the next interval. If they overlap, merge them by creating a new interval with the minimum start time and maximum end time.

Time Complexity: O(n log n) due to the sorting step. The merging step is O(n). Space Complexity: O(n) in the worst case, as we may need to create a new array to store the merged intervals. This excludes the space used by the input and output arrays themselves.

Approach 2: One-Pass Traversal

This approach offers an optimized solution by performing the insertion and merging in a single pass:

  1. Initialization: Initialize an empty result array ans and variables to track the newInterval's start and end. Also, use a boolean flag inserted to track whether the newInterval has already been added.

  2. Iteration: Iterate through the input intervals. For each interval:

    • If the current interval's start is greater than the newInterval's end (ed < s), and the newInterval hasn't been inserted yet, insert the newInterval into the ans. Then add the current interval to ans.
    • If the current interval's end is less than the newInterval's start (e < st), add the current interval to ans.
    • Otherwise, there's overlap. Update newInterval's start and end to cover the entire range of the merged interval.
  3. Final Insertion: After the loop, if the newInterval hasn't been inserted, append it to ans.

Time Complexity: O(n) as we iterate through the array only once. Space Complexity: O(n) in the worst case, to store the result. Again, this excludes the input and output arrays.

Code Examples (Python):

Approach 1:

def insert(intervals, newInterval):
    intervals.append(newInterval)
    intervals.sort()
    merged = []
    for i in intervals:
        if not merged or i[0] > merged[-1][1]:
            merged.append(i)
        else:
            merged[-1][1] = max(merged[-1][1], i[1])
    return merged

Approach 2:

def insert(intervals, newInterval):
    st, ed = newInterval
    ans = []
    inserted = False
    for s, e in intervals:
        if ed < s:
            if not inserted:
                ans.append([st, ed])
                inserted = True
            ans.append([s, e])
        elif e < st:
            ans.append([s, e])
        else:
            st = min(st, s)
            ed = max(ed, e)
    if not inserted:
        ans.append([st, ed])
    return ans
 

The code examples in other languages (Java, C++, Go, TypeScript, Rust, C#) follow similar logic based on the chosen approach. Remember to choose the approach that best suits your needs. For large datasets, the one-pass traversal (Approach 2) provides a significant performance advantage.