57. Insert Interval

Overview
Insert the new interval into intervals array.
If the new intervals crosses several intervals, they should combine into one interval.
Solution 1: Linear Search
Algorithm
- Initialize
nas the length of intervals.
iwill point to index we're current handling, defaulting to 0.
Initialize a new listanswerto save the interval results.
Destructurenew_intervalintonew_startandnew_endfor increased readable.

- Check if
current interval endis smaller thannew_start.
It means thecurrent intervalis entirely before thenew internal.
Append thecurrent intervalto theanswer.

- Check if
new_endis greater than or equals tocurrent interval start
It means thenew intervalshould combine with thecurrent interval.
Append thenew intervalto theanswerafter all combining is finished.

- Check if there still some intervals not appended to the answer.
Append the
remaining intervalsto theanswer.
Implement
class Solution: def insert( self, intervals: list[list[int]], new_interval: list[int], ) -> list[list[int]]: n = len(intervals) i = 0 answer: list[list[int]] = [] new_start, new_end = new_interval while i < n and intervals[i][1] < new_start: answer.append(intervals[i]) i += 1 while i < n and new_end >= intervals[i][0]: new_start = min(new_start, intervals[i][0]) new_end = max(new_end, intervals[i][1]) i += 1 answer.append([new_start, new_end]) while i < n: answer.append(intervals[i]) i += 1 return answer
Complexity Analysis
Time complexity: O(n)
The variable i will increase from 0 to n.
We only iterate through the intervals once.
Space complexity: O(1)
We only use an additional list for saving the answer.