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
n
as the length of intervals.
i
will point to index we're current handling, defaulting to 0.
Initialize a new listanswer
to save the interval results.
Destructurenew_interval
intonew_start
andnew_end
for increased readable.

- Check if
current interval end
is smaller thannew_start
.
It means thecurrent interval
is entirely before thenew internal
.
Append thecurrent interval
to theanswer
.

- Check if
new_end
is greater than or equals tocurrent interval start
It means thenew interval
should combine with thecurrent interval
.
Append thenew interval
to theanswer
after all combining is finished.

- Check if there still some intervals not appended to the answer.
Append the
remaining intervals
to 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.