Insert Interval

medium

You are given a set of non-overlapping intervals sorted by start time, where each intervals[i] = [start, end], plus a newInterval = [start, end]. Insert newInterval into the set, merging with any intervals it overlaps, and return the resulting set of non-overlapping intervals, still sorted by start time.

Intervals that touch at an endpoint are considered to overlap and should be merged.

Hints

The given intervals are already sorted and disjoint — do you really need to sort again?
Split the intervals into three groups: entirely before the new one, overlapping it, entirely after.
Merge the overlapping group by taking the min start and max end, then emit one interval.

Common doubts

The input is already sorted and non-overlapping, so no sort is needed — a single left-to-right pass handles the before / merge / after phases in order.
Touching intervals overlap for this problem: an interval starting exactly at the new interval's end must be merged, so the comparison is inclusive.
Then the merge phase runs zero times and newInterval is emitted as its own interval between the before and after groups.

Interview follow-ups

Fall back to the general merge-intervals approach: add newInterval, sort by start, and merge — that's the O(n log n) brute force here.
Either apply the three-phase insert repeatedly, or collect them all and run a single sort-and-merge over everything.

Fun facts

  • This is 'Merge Intervals' with a shortcut: knowing the input is pre-sorted removes the sort and drops it to linear time.
  • The three-phase structure — skip, absorb, copy — is a common shape for one-pass interval algorithms.

Asked at

GoogleAmazonMetaMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
The new interval [2,5] overlaps [1,3], merging into [1,5]; [6,9] is untouched.
Example 2
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
[4,8] overlaps [3,5], [6,7], and [8,10], merging them all into [3,10].
Constraints

- 0 <= intervals.length <= 10^4 - intervals is sorted by start and has no overlapping intervals - newInterval.length == 2 and start <= end

Solve this problem →