Skip to content
Advertisement

Interval insert by exclusively adding an interval to a list of intervals

This is similar to this problem: https://leetcode.com/problems/insert-interval/

However, what I need is a bit different. I need to lower the smallest interval by 1 if to compare with the one I want to add and increase the next closest interval by one to with the one I want to add if there are intersections.

Say I have:

  • intervals: [0, 3],[4, 4],[5, 5] and I want to insert [3, 3], the result should be [[0, 2], [3, 3], [4, 4], [5,5]]

  • If I have intervals: [0, 3],[4, 4],[5, 5] and I want to insert [3, 4], the result should be [[0, 2], [3, 4], [5,5]]

  • If I have intervals: [0, 3],[4, 8],[9, 10] and I want to insert [5, 7], the result should be [[0, 3], [4, 4], [5, 7], [8, 8] [9, 10]]

Is there any efficient way to do it?

One important thing is that the interval I want to insert will always be between 0 and the last number of the current interval list. In the above examples, it would be between 0 and 5; 0 and 5; 0 and 10

This is my code which was unsuccessful:

JavaScript

While it passes test cases 1-5, I always find a test case which does not pass meaning that my solution is buggy.

Advertisement

Answer

This code works but it is not optimized. I believe the use of operations on sets leads to efficient computing thow:

JavaScript

Example : split(set([1,2,3,4,5,7])): [[1, 5], [7, 7]]

JavaScript

Example: merge([[0, 3], [4, 4], [5, 7], [8, 8], [8, 10]]): [[0, 3], [4, 4], [5, 7], [8, 10]]

JavaScript

Example: insert([[0, 3],[4, 8],[5, 10]], [5,7]): [[0, 3], [4, 4], [5, 7], [8, 10]]

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement