Naive solution
class Solution:
def insert(self, A: List[List[int]], B: List[int]) -> List[List[int]]:
"""
main idea: for non-overlap intevals, if interval is smaller than B, updating pointer to be inserted; if interval is bigger than B, just push it into res; === for overlaped intevals, keep updating longest inteval overlap with B, update B
after iteration A is complete, inset target index for findal B
tc O(2N) sc O(1)
"""
res = []
n = len(A)
if not A:
return [B]
cur = 0
res = []
for i,pair in enumerate(A):
s,e = pair
# non-overlap (1) end < new_start (2) start > new_end
if e < B[0] :
res.append(pair)
cur += 1
elif s > B[1]:
res.append(pair)
else:
B = [min(s,B[0]),max(e,B[1])]
res.insert(cur,B)
return res
Optimization: update B in place
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
""" time O(N) space: O(1)
main idea: use 3 loops to seperate different non-overlap inteverse
edge case: intvs is empty
case 1: intv end < new_start
case_2: intv_start <= new_end, note intv_start == new_end will meet overlap condition, don missout
case_3: intv_start > new_start
"""
if not A:
return [B]
n,i = len(A),0
res = []
while i < n and A[i][1] < B[0]:
res.append(A[i])
i += 1
while i < n and A[i][0] <= B[1]:# and B[0]<=A[i][1]: # cross check if not necessary since we are extending B with overlapping inteval insead of finding intersections
B = [min(B[0],A[i][0]),max(A[i][1],B[1])]
i += 1
# note, keep updating B until there is no overlapping, then put final B into res
res.append(B)
while i < n and A[i][0] > B[1]:
res.append(A[i])
i += 1
return res