LC 0057 [M] Insert Interval - ALawliet/algorithms GitHub Wiki
https://www.youtube.com/watch?v=A8NUOmlwOlM&ab_channel=NeetCode
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
for i in range(len(intervals)):
curInterval = intervals[i]
if newInterval[1] < curInterval[0]: # new interval ends before current, no overlap with left or right
res.append(newInterval)
return res + intervals[i:] # return the rest and bail early
elif newInterval[0] > curInterval[1]: # new interval starts after current, no overlap with left but could overlap with right
res.append(curInterval)
else: # is overlap, so merge with min start and max end
newInterval = [min(newInterval[0], curInterval[0]), max(newInterval[1], curInterval[1])]
res.append(newInterval)
return res