57_Insert Interval

[Hard][Array, Sort]

Given a set of _non-overlapping _intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

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

Idea:

  • First search for the position where we should insert or merge the new interval. The intervals on the left will be neglected.

  • Then search for the position where we end insertion or merge. The intervals on the right will be neglected.

  • Finally insert or merge the new interval.

Time Complexity: O(n)O(n)

Space Complexity: O(1)O(1)

Idea:

  • Extract all the starting values from the intervals, find the right place to insert the starting point in the new interval by binary search

  • Extract all the ending values from the intervals, find the right place to insert the ending point in the new interval bu binary search

  • Insert or merge the new interval into the overlapping place.

Time Complexity: O(logn)O(\log{n})

Space Complexity: O(1)O(1)

Last updated

Was this helpful?