Skip to content

Instantly share code, notes, and snippets.

@shamod
Last active July 21, 2020 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shamod/fa62498cfa9afd8512d509fc18ac1bd3 to your computer and use it in GitHub Desktop.
Save shamod/fa62498cfa9afd8512d509fc18ac1bd3 to your computer and use it in GitHub Desktop.
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
'''
Test cases
i) [], [2,5] => [[2,5]]
ii) [[1,3]], [2,5] => [[1,5]]
iii) [[1,3],[6,9]], [2, 5] => [[1,5], [6,9]]
iv) [[1,3],[4,9], [10,15]], [2, 11] => [[1, 15]]
v) [[0,1],[2,3],[4,9], [10,15], [16, 20]], [2, 11] => [[0,1], [2, 15], [16,20]]
vi) [[1,2],[3,5],[6,7],[8,10],[12,16]],[4,8] => [[1,2], [3,10], [12,16]]
New: [2, 15]
Curr [16, 20]
Interval: [2, 15]
Res: [[0,1]]
1. Loop through the intervals
Current interval
Check if isOverlapping(current interval, newinterval)
If yes, merge the new interval
newInterval = merged interval
Else:
Commit the new interval to the result array
Merge function (interval1, interval2)
interval.start = min(interval1.start, interval2.start)
interval.end = max(interval1.end, interval2,end)
IsOverlapping function(currinterval, newinterval):
return currinterval.start <= newinterval.start <= currinterval.end or
newinterval.start <= currinterval.start <= newinterval.end
'''
def mergeIntervals(interval1, interval2):
return [min(interval1[0], interval2[0]), max(interval1[1], interval2[1])]
def isOverlapping(currinterval, newinterval):
return currinterval[0] <= newinterval[0] <= currinterval[1] or \
newinterval[0] <= currinterval[0] <= newinterval[1]
n = len(intervals)
res = []
if n == 0:
res.append(newInterval)
return res
i = 0
while i < n:
if isOverlapping(intervals[i], newInterval): break
if newInterval[0] < intervals[i][0]:
res.append(newInterval)
newInterval = []
break
else:
res.append(intervals[i])
i += 1
while i < n:
curr_interval = intervals[i]
if len(newInterval) > 0 and isOverlapping(curr_interval, newInterval):
newInterval = mergeIntervals(curr_interval, newInterval)
else: break
i += 1
if len(newInterval) > 0: res.append(newInterval)
while i < n:
res.append(intervals[i])
i += 1
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment