Problem
Problem page: https://leetcode.com/problems/insert-interval/
Topics: Array, Sort
Difficulty: Hard
Similar problems: (H) Merge Intervals
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:
Given intervals[1,3],[6,9], insert and merge[2,5]in as[1,5],[6,9].Example 2:
Given[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge[4,9]in as[1,2],[3,10],[12,16].This is because the new interval
[4,9]overlaps with[3,5],[6,7],[8,10].
Analysis
First, I need to find where newInterval fits in the existing array. There are four possibilities:
- newInterval doesn't overlap any interval in the array and lies to the left of them all, so left_index=0 and right_index=-1. Just insert newInterval at the start of the array.
- There's no overlap here either, but newInterval lies to the right of all the intervals, so left_index=-1. Append newInterval to the array.
- newInterval falls in the gap between two adjacent intervals, so left_index points to the interval on the right side of the gap and right_index=-1. Insert newInterval just before the interval that left_index points to.
- newInterval overlaps just one interval in the array or spans several. This is the most common case. Here left_index points to the smallest interval in the array whose right endpoint is >= the left endpoint of newInterval (I treat intervals farther to the right on the number line as larger), and right_index points to the largest interval in the array whose left endpoint is <= the right endpoint of newInterval, so the range of the array that newInterval affects runs from left_index to right_index. I can copy everything outside that range into the result array as is. I need to merge the intervals inside the range with newInterval to make a single interval (add_interval in the code), then add it to the result array.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-insert-interval/
