Three parts of the list
Imagine slotting a new meeting into a sorted calendar. Walk the list once. First, copy every interval that ends before the new one starts: they can't touch it.
Next, every interval that starts at or before the new one's end overlaps it, so absorb it by widening the new interval. Then add the widened interval and copy the rest unchanged.
Before: ends before the new start: copy it.
Absorb: starts by the new end: take the earlier start and the later end.
After: everything left starts past the end: copy it.
result = []
start, end = added
i, n = 0, len(intervals)
while i < n and intervals[i][1] < start:
result.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= end:
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i += 1
result.append([start, end])
result.extend(intervals[i:])
return resultInsert [4, 8] into [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]]
[1, 2] ends before the new one starts at 4. It can't touch it: copy it.
Move 1 of 4
Trace it
List [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], new [4, 8]. [1, 2] ends before 4: copy. [3, 5], [6, 7] and [8, 10] all start at or before 8, so absorb them, giving [3, 10]. Add it, then copy [12, 16].
Result: [[1, 2], [3, 10], [12, 16]].
Widen both ends: absorbing [3, 5] moves the start back to 3.
Nothing touched: if no interval overlaps, the new one simply slots in.