π57. Insert Interval
Medium | Grind 75 | August 29th Monday, 2022
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.
Constraints:
0 <= intervals.length <= 10^4intervals[i].length == 20 <= starti <= endi <= 10^5intervalsis sorted bystartiin ascending order.newInterval.length == 20 <= start <= end <= 10^5
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]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].SOLUTION
We will first add the new interval to the intervals list and sort the list. NOTE: it is important to sort the interval list because our merge algorithm assume the list is sorted. Once we have sorted the interval list, we will now perform the merging of the intervals.
iterate over every element in the intervals list.
Take the first element in the interval list.
store the intervals of the current element as
startandend.
In order to find intervals that overlap, check if the
startvalue is equal to thestart of the next elementor the current end value is greater than thestart value of next element. If yes:set the
startas the minimum of currentstartand thenext element start.set the
endas the maxmimum of currentendand theend value of the next element.look at the next next element and compare to
startandendvalue.
Append the
startandendvalue in your newmerged interval list.
TIME AND SPACE COMPLEXITY
TIME: O(nlogn) where n is the length of the interval list. We get a runtime of O(nlogn) because of the sort that we perform after adding the new interval in the list. You could on average have a better runtime(O(n)) with a different solution but in the worst case, even that solution will be O(nlogn)
SPACE: O(n) our new merged intervals in the worst case will store n+1 elements.
Last updated