November 12, 2024
This took me a long time to cover all cases.
1class Solution:2 def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:3 start, end = newInterval4 inserted = False5 res = []6 for item in intervals:7 if end < item[0]:8 if not inserted:9 res.append([start, end])10 inserted = True11 res.append(item)12 elif end >= item[0] and end <= item[1]:13 start = item[0] if item[0] < start else start14 end = item[1]15 elif start >= item[0] and end <= item[1]:16 start, end = item17 res.append([start, end])18 inserted = True19 elif start >= item[0] and start <= item[1] and end > item[1]:20 start = item[0]21 elif start > item[1]:22 res.append(item)2324 if not inserted:25 res.append([start, end])26 return res
O(n) = n since we iterate over all elements once.
This solution has the same complexity, but it is simpler thereby being more maintanable.
1class Solution:2 def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:3 res = []4 n = len(intervals)56 i = 07 while i < n and intervals[i][1] < newInterval[0]:8 res.append(intervals[i])9 i += 11011 while i < n and newInterval[1] >= intervals[i][0]:12 newInterval[0] = min(intervals[i][0], newInterval[0])13 newInterval[1] = max(intervals[i][1], newInterval[1])14 i += 11516 res.append(newInterval)17 res.extend(intervals[i:])1819 return res
LeetCode 56. Merge Intervals
LeetCode 150. Evaluate Reverse Polish Notation