Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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.
In code
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 result
Insert [4, 8] into [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]]
13579111315[1, 2][3, 5][6, 7][8, 10][12, 16]newanswer

[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.