PracticeNeetCode ↗LeetCode ↗
Given a list of non-overlapping intervals sorted by start time, and a new interval, insert the new interval into the list — merging any intervals it overlaps with — and return the resulting non-overlapping, sorted list.
newInterval starts — they need no merging.newInterval (its start is at or before newInterval's end), absorb it by extending newInterval's start/end to the min/max of the two.newInterval to the result.newInterval now ends.Time: O(n) — Space: O(n) for the output
def insert(intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:
result = []
i = 0
n = len(intervals)
while i < n and intervals[i][1] < newInterval[0]:
result.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
result.append(newInterval)
while i < n:
result.append(intervals[i])
i += 1
return resultHow the solution above works, piece by piece.
newInterval starts.newInterval ends, they overlap; stretch newInterval to cover both. Then append it once.Running it on intervals = [[1, 3], [6, 9]], newInterval = [2, 5]: