Problem 39 · Intervals
Insert Interval
01Problem
Given sorted non-overlapping intervals and a new interval, insert it and merge as needed, returning sorted non-overlapping intervals.
02Key insight
Three linear phases: copy intervals ending before the new one, absorb all that overlap by widening the new interval, then copy the rest. No re-sort needed.
03Solution
Try it first.
TimeO(n)
SpaceO(n)
tests.py · 4 passing
tests.pypython4 lines
assert insert_interval([[1, 3], [6, 9]], [2, 5]) == [[1, 5], [6, 9]]
assert insert_interval([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]) == [[1, 2], [3, 10], [12, 16]]
assert insert_interval([], [5, 7]) == [[5, 7]]
assert insert_interval([[1, 5]], [6, 8]) == [[1, 5], [6, 8]]04Staff-level follow-up
Millions of intervals and frequent inserts? Binary-search (bisect) the overlap range for O(log n) location, though splicing a Python list is still O(n); use an interval tree or SortedList for true O(log n).