You are given an array of non-overlapping intervals intervals sorted by start. Insert newInterval in the correct position (merge if necessary).
intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8][[1,2],[3,10],[12,16]]end < new.startnew = [min(new[0],iv[0]), max(new[1],iv[1])]Intervals are sorted. Phase 1 adds those entirely before the new interval. Phase 2 merges all overlapping intervals in one pass. Phase 3 adds those entirely after.
You could append the new interval, sort everything, and run merge intervals. But the list is already sorted, so one linear scan is enough.
First, copy every interval that ends before the new one starts. Then, while intervals start before the new one ends, merge them into it by widening its start and end. Finally, add the merged interval and copy everything after it.
Before, overlapping, after. Three simple loops, and no sorting.
Run the animation above on your own input, or watch the 1:24 video explanation of Insert Interval with a dry run and Java code.