Insert Interval
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
You're given a list of non-overlapping intervals intervals, sorted by start, and one more interval newInterval.
Insert newInterval so that the list stays sorted and non-overlapping, merging it with any intervals it overlaps or touches. Return the resulting list.
Understand the problem
- An interval
[start, end]is a range of numbers fromstarttoend. - Merging two overlapping intervals means replacing them with one interval that covers both:
[1, 3]and[2, 5]become[1, 5]. - For this problem, intervals that touch (like
[1, 5]and[5, 7]) are merged too. - The input list is already sorted and has no overlaps. Only
newIntervalmight cause overlaps.
Example 1
Input: intervals = [[1, 3], [6, 9]], newInterval = [2, 5]
Output: [[1, 5], [6, 9]][2, 5] overlaps [1, 3], so they merge into [1, 5].
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 touches [8, 10]: all four merge into [3, 10].
Example 3
Input: intervals = [], newInterval = [5, 7]
Output: [[5, 7]]Constraints
0 <= intervals.length <= 10^40 <= start <= end <= 10^5
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Walk the sorted list once: copy the intervals that come entirely before the new one, swallow the ones that overlap it by widening it, add it, then copy the rest.
The naive approach
Append newInterval and run Merge Intervals: sort and merge. It's correct, but sorting costs O(n log n), and the list was already sorted. We can do better.
The key insight: three groups, in order
Because the list is sorted and has no overlaps, every interval falls into one of three groups compared with newInterval, and the groups appear in this order:
-
Entirely before it: the interval ends before
newIntervalstarts (end < newStart). Copy it unchanged. -
Overlapping it: the interval starts at or before
newInterval's end (start <= newEnd). Merge it in by wideningnewInterval:newStart = min(newStart, start)newEnd = max(newEnd, end)
When this group is done, add the widened
newIntervalonce. -
Entirely after it: everything else. Copy unchanged.
number line: 1 2 3 4 5 6 7 8 9 10 11 12 ... 16
existing: [1-2] [3--5] [6-7] [8---10] [12 ----- 16]
new: [4---------8]
result: [1-2] [3--------------10] [12 ----- 16]Step by step
intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], newInterval = [4, 8]:
| Interval | Check | Group | newInterval after | Result so far |
|---|---|---|---|---|
[1, 2] | 2 < 4: ends before | before | [4, 8] | [1, 2] |
[3, 5] | 3 <= 8: overlaps | merge | [3, 8] | [1, 2] |
[6, 7] | 6 <= 8: overlaps | merge | [3, 8] | [1, 2] |
[8, 10] | 8 <= 8: touches | merge | [3, 10] | [1, 2] |
[12, 16] | 12 > 10: stop merging | after | add [3, 10] | [1, 2], [3, 10] |
| copy the rest | [1, 2], [3, 10], [12, 16] |
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). One pass, no sorting.
- Memory: O(n) for the result.
Common mistakes
- Comparing the wrong ends. "Before" means the existing interval's end is less than the new start; "overlaps" means the existing start is at most the new end.
- Adding the merged interval inside the loop, once per overlap, instead of once after the merge phase.
- Forgetting the empty list, or a new interval that goes at the very start or the very end. The three-phase loop handles all of these if written carefully.
- Mutating the input arrays while widening. The code uses separate
startandendvariables.
Going deeper
Merge Intervals solves the general case where the list isn't sorted. This problem shows how much an already-sorted input helps: O(n) instead of O(n log n).
Reference solution
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
export default function insert(intervals, newInterval) {
const result = []
let [start, end] = newInterval // the new interval, widened as it swallows overlaps
let i = 0
// 1. Entirely before: ends before the new interval starts. Copy unchanged.
while (i < intervals.length && intervals[i][1] < start) result.push(intervals[i++])
// 2. Overlapping (or touching): starts at or before the new end. Widen to cover it.
while (i < intervals.length && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0])
end = Math.max(end, intervals[i][1])
i++
}
result.push([start, end]) // the merged interval, added once
// 3. Entirely after: copy the rest unchanged.
while (i < intervals.length) result.push(intervals[i++])
return result
}export default function insert(intervals: number[][], newInterval: number[]): number[][] {
const result: number[][] = []
let [start, end] = newInterval // the new interval, widened as it swallows overlaps
let i = 0
// 1. Entirely before: ends before the new interval starts. Copy unchanged.
while (i < intervals.length && intervals[i][1] < start) result.push(intervals[i++])
// 2. Overlapping (or touching): starts at or before the new end. Widen to cover it.
while (i < intervals.length && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0])
end = Math.max(end, intervals[i][1])
i++
}
result.push([start, end]) // the merged interval, added once
// 3. Entirely after: copy the rest unchanged.
while (i < intervals.length) result.push(intervals[i++])
return result
}def insert(intervals: list[list[int]], new_interval: list[int]) -> list[list[int]]:
result = []
start, end = new_interval # the new interval, widened as it swallows overlaps
i = 0
# 1. Entirely before: ends before the new interval starts. Copy unchanged.
while i < len(intervals) and intervals[i][1] < start:
result.append(intervals[i])
i += 1
# 2. Overlapping (or touching): starts at or before the new end. Widen to cover it.
while i < len(intervals) and intervals[i][0] <= end:
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i += 1
result.append([start, end]) # the merged interval, added once
# 3. Entirely after: copy the rest unchanged.
result.extend(intervals[i:])
return result