Insert Interval
1 approach, code in every language
Problem description
You start with a list of non-overlapping intervals that is already ordered by start value. A single new interval arrives, and you must slot it into the list so that the final collection stays sorted and free of overlaps, merging with any existing intervals that it touches.
Return the updated list. Because the original data is presorted, a full re-sort is unnecessary; a single linear pass can place and merge the newcomer.
Example 1
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
The new range 2-5 overlaps 1-3, so they fuse into 1-5 while 6-9 stays untouched.
Example 2
Input: intervals = [[1,2],[3,5],[6,7],[8,10]], newInterval = [4,8]
Output: [[1,2],[3,10]]
4-8 spans 3-5, 6-7 and 8-10, collapsing all three into 3-10.
Constraints
0 ≤ intervals.length ≤ 10^4intervals[i].length == 2 and newInterval.length == 20 ≤ start ≤ end ≤ 10^5intervals is sorted by start in ascending order with no overlaps
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Slot a New Rehearsal Block is our own problem on the technique behind Insert Interval: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free