Leetcode 57: Insert Interval

https://leetcode.com/problems/insert-interval/

Insert Interval

Total Accepted: 43188 Total Submissions: 196069 Difficulty: Hard

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

Code

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def insert(self, intervals, newInterval):
        """
        :type intervals: List[Interval]
        :type newInterval: Interval
        :rtype: List[Interval]
        """
        if not intervals:
            return [newInterval]
        strt_idx = self.binary_search(intervals, newInterval.start)        
        end_idx = self.binary_search(intervals, newInterval.end)
        
        if strt_idx ==0 and newInterval.end < intervals[0].start:    # Condition 1
            intervals[0:1] = [newInterval, intervals[0]]
        elif newInterval.start > intervals[strt_idx].end:            # Condition 2
            intervals[strt_idx:end_idx+1] = [intervals[strt_idx], 
                                             Interval(newInterval.start, max(intervals[end_idx].end, newInterval.end))]
        else:                                                        # Condition 3
            intervals[strt_idx:end_idx+1] = [Interval(min(intervals[strt_idx].start, newInterval.start), 
                                             max(intervals[end_idx].end, newInterval.end))]
        return intervals

    def binary_search(self, intervals, t):
        left, right = 0, len(intervals)-1
        while left <= right:
            mid = (left + right) / 2
            if t > intervals[mid].start:
                left = mid + 1
            elif t < intervals[mid].start:
                right = mid - 1
            else:
                return mid
        
        # return index where t >= intervals[index].start
        return left-1 if left - 1 >=0 else 0
        


Idea

Do two rounds of binary search to determine the rightmost interval in `intervals` whose start $latex \leq$ `newInterval.start`. Also determine the rightmost interval whose start $latex \leq$ `newInterval.end`. Then you have three situations to deal with:

ii

Leave a comment

Your email address will not be published. Required fields are marked *