Insert Interval
Problem
You have a list of non-overlapping intervals sorted by start, and one new interval. Insert the new interval so the list stays sorted and non-overlapping, merging wherever necessary, and return the result.
Examples
Constraints
- • 0 <= intervals.length <= 10^4
- • intervals is sorted by start and non-overlapping
- • 0 <= start <= end <= 10^5
Hints & approach
Hint 1
The input is already sorted, so you do not need to sort again.
Hint 2
Split the list into three parts: entirely before the new interval, overlapping it, and entirely after.
Hint 3
Everything in the middle part collapses into one interval with the min start and max end.
Approachtry the hints first
Scan once. Copy every interval that ends before the new one starts. Then, while intervals start at or before the new interval's end, absorb them by taking the minimum start and maximum end. Append the merged interval, then copy the remaining intervals unchanged. This is a single linear pass with no sorting.
Time O(n) · Space O(n)