DEV Community

Bernice Waweru
Bernice Waweru

Posted on

1

Insert Interval

Instructions

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

Example

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

Approach

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.

Implementation

def insert(intervals, newInterval):

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

        result.append(newInterval)

        return result
Enter fullscreen mode Exit fullscreen mode

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

Happy learning!!

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay