[LC 57] Insert Interval

Solution

Posted by jyaquinas on April 02, 2022 · 3 mins read

LeetCode 57

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.

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

One way we could solve this would be to add the new interval to the list, then sort it based on the starting indices, which would give us a time of O(nlogn). This would then be the same as the Merge Intervals problem.

But this method doesn’t take advantage of the fact that the intervals are already sorted. What we need to do is go through the sorted intervals and see at which point we have to insert the new interval.

We have a couple cases to consider:

  • The entire new interval comes before the next interval (no overlap). We would then have to add the new interval at that location, and then add the rest of the intervals after that (since we already inserted the new interval).
  • The entire new interval comes after the next interval (also no overlap). We add the next interval, not the new interval.
  • It overlaps, and the new interval would be the minimum of the starting indices, and the maximum of the ending indices. We don’t add the new interval yet because it could overlap the other intervals.

Here’s the implementation:

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        res = []
        for i, interval in enumerate(intervals):
            if newInterval[1] < interval[0]:
                res.append(newInterval)
                res.extend(intervals[i:])
                return res
            elif newInterval[0] > interval[1]:
                res.append(interval)
            else:   # overlaps
                start = min(newInterval[0], interval[0])
                end = max(newInterval[1], interval[1])
                newInterval = [start, end]
        res.append(newInterval)
        return res

Time: O(n)
Space: O(n)