Insert Interval – Solution & Complexity
Solution Walkthrough
1. Understand the Goal
intervalsarrives pre-sorted and non-overlapping, so the only disorder in the whole array comes from insertingnewIntervalonce.- Because of that guarantee, you never need a general sort or an O(n^2) overlap check — a single left-to-right scan is enough to find exactly where the new interval lands.
2. Choose the Core Pattern
- Split the array into three contiguous phases relative to
newInterval: intervals that end strictly before it starts, intervals that overlap it, and intervals that start strictly after it ends. - "Overlap" here includes endpoint-touching intervals like
[1,2]and[2,3]— treat<=/>=(not strict</>) as the overlap test, since a merged[1,3]is still a single valid interval and keeping[1,2],[2,3]separate would be a needlessly fragmented answer.
3. Build the Algorithm
- Phase 1: while the current interval's end is strictly less than the new interval's start, it can't overlap — copy it through unchanged.
- Phase 2: while the current interval's start is <= the new interval's end, they touch or overlap — absorb it by taking the min of starts and max of ends, growing
newIntervalin place rather than emitting anything yet. - After phase 2 ends (or immediately if it never ran), emit the now-final merged interval exactly once.
- Phase 3: copy every remaining interval through unchanged — by definition none of them can touch the merged interval, since the scan already passed the last one that could.
4. Check Edge Cases
- Empty
intervals: phases 1 and 3 run zero times and phase 2 also runs zero times, so the result is just[newInterval]. newIntervalfits entirely before the first interval or after the last: it participates in zero merges and is emitted as its own entry in the correct position.newIntervalfully contains one or more existing intervals: the min/max absorption in phase 2 naturally swallows them without special-casing containment separately from partial overlap.
5. Final Solution and Complexity
- Time complexity is O(n).
- Space complexity is O(n).