Insert Interval
You are given a list intervals of non-overlapping intervals [start, end], sorted by start, and a new interval newInterval = [start, end]. Insert newInterval into the list so that the list stays sorted and has no overlapping intervals, merging any intervals that overlap it. Return the resulting list.
Intervals that share an endpoint, such as [1, 3] and [3, 5], overlap and are merged into [1, 5].
Examples
The highlighted bar is newInterval.
The highlighted bar is newInterval.
The highlighted bar is newInterval.
Constraints
- 0 <= intervals.length <= 10,000
- intervals[i] = [start, end] with 0 <= start <= end <= 100,000
- intervals is sorted by start and its intervals do not overlap
- newInterval = [start, end] with 0 <= start <= end <= 100,000
Stuck? Take one hint at a time
Common mistakes
- Treating touching intervals as separate: [1, 3] and [3, 5] overlap here, so the condition is "starts at or before the end", not "starts before".
- Using "ends at or before" in the first loop, which would copy an interval that touches the new interval instead of merging it.
- Adding the merged interval inside the second loop, once per absorbed interval, instead of once after it.
- Taking the new start and end from the first overlapping interval only, instead of the minimum start and the maximum end across all of them.
- Sorting by end instead of start in the sort based version.
Questions an interviewer may ask next
- Remove an interval from the list instead of inserting one. (Intervals that overlap it are cut, and may split in two.)
- The intervals are stored in a balanced tree or skip list. Which operation gives O(log n + k) for inserting, where k is the number merged?
- Insert many new intervals one after another. What data structure makes each insertion cheap? (An ordered map keyed by start.)
- Count how many intervals the insertion merged, without building the answer.
How often this is reported
Grade C: Reported in one source, or backed mainly by volume of reports. This reflects what candidates report, not a guarantee of what any company will ask.
[[1,3],[6,9]]
[2,5]
[[1,5],[6,9]]
Run checks these cases. Submit also runs hidden cases, and shows you the first one that fails.