DEV Community

Bernice Waweru
Bernice Waweru

Posted on

Insert Interval


Insert newInterval into intervals such that intervals is still sorted in ascending order and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

Attempt here


Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Enter fullscreen mode Exit fullscreen mode


Since the input is sorted, we can check if the end value of newInterval is less than the start value of the elements in the intervals list.

If the endtime of the newInterval is less than start[i][0] then we insert it in the results variable then insert the remaining intervals because output should be in ascending order.

If the starttime of the newInterval is greater than the endtime of a given interval then we append the interval to the results

For overlapping intervals, we merge them by geting the start value as the minimum of the two starts and the end value as the maximum of the end values.
Append new interval to result and return result.


def insert(intervals, newInterval):

        result = []
        for i in range(len(intervals)):
            if newInterval[1] < intervals[i][0]:
                return result + intervals[i:]
            elif newInterval[0] > intervals[i][1]:
                newInterval = [min(newInterval[0],intervals[i][0]), max(newInterval[1],intervals[i][1])]


        return result
Enter fullscreen mode Exit fullscreen mode

This runs in O(n) time complexity and O(n) space complexity.

Happy learning!!

Top comments (0)