Time: → Reason: Potentially all intervals may be merged
Space: → Reason: Result array
Code
class Solution:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
if not intervals:
return [newInterval]
newStart, newEnd = newInterval
isInserted = False
for i, (curStart, curEnd) in enumerate(intervals):
if newStart <= curStart:
intervals.insert(i, newInterval)
isInserted = True
break
if not isInserted: # insert at the end
intervals.append(newInterval)
result = []
prev = None
for curStart, curEnd in intervals:
if not prev:
prev = [curStart, curEnd]
continue
prevStart, prevEnd = prev
if curStart <= prevEnd:
prev = [prevStart, max(prevEnd, curEnd)]
else:
result.append(prev)
prev = [curStart, curEnd]
if prev:
result.append(prev)
return result
Common Mistakes / Things I Got Stuck On
Not being able to come up with the high level algorithm on how to insert the new interval