You are given intervals, a list of ranges [start, end]. The list is sorted by start, and no two ranges in it overlap. You are also given one more range, newInterval.
Add newInterval to the list. Wherever it overlaps existing ranges, combine them into one. Two ranges overlap if they share at least one point, so [1, 3] and [3, 5] become [1, 5].
Return the new list, still sorted by start and with no overlaps. You may build a fresh list instead of changing the input.
Example 1
Input: intervals = [[1, 4], [7, 10]], newInterval = [3, 6] Output: [[1, 6], [7, 10]] Why: [3, 6] overlaps [1, 4] only
2 more examples and the constraints
Example 2
Input: intervals = [[0, 1], [2, 4], [5, 6], [8, 9], [11, 14]], newInterval = [3, 8] Output: [[0, 1], [2, 9], [11, 14]] Why: [3, 8] touches [2, 4], [5, 6] and [8, 9]
Example 3
Input: intervals = [[1, 2], [9, 12]], newInterval = [4, 6] Output: [[1, 2], [4, 6], [9, 12]] Why: no overlap; it slots into the gap
Constraints
- 0 ≤ number of intervals ≤ 10,000
- 0 ≤ start ≤ end ≤ 100,000 for every range, including newInterval
- intervals is sorted by start and has no overlapping ranges
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Add, sort, mergeO(n log n)
- One pass in three runsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 intervals | Verdict |
|---|---|---|---|
| Add, sort, merge | O(n log n) | Passes; re-sorts a sorted list | |
| One pass in three runs | O(n) | Best; one sweep, done |
n = how many intervals are in the list.
Edge cases to test
- Empty list. [] with [4, 7] gives [[4, 7]]: the new range alone.
- Touching ends. [[1, 3], [6, 8]] with [3, 6] gives [[1, 8]]: sharing a point is overlap.
- New range swallows everything. [[2, 3], [5, 6]] with [0, 10] gives [[0, 10]].
- New range inside one range. [[1, 10]] with [4, 5] gives [[1, 10]] unchanged.
- Goes first or last. With no overlap the new range lands at the very front or very back.
Common mistakes
- Using < instead of ≤ when checking overlap, so [1, 3] and [3, 5] stay apart.
- Forgetting to add the merged range when the loop ends, so a new range at the back vanishes.
- Keeping the new start fixed while absorbing, instead of taking the smaller start.
How to talk through it
- 1Clarify. Do ranges that share one endpoint count as overlapping? Can the list be empty?
- 2Give the simple version. Add the range, sort, merge. Say it is O(n log n) and ignores that the list is sorted.
- 3Name the three runs. Before, overlapping, after. The sorted order means each run is contiguous.
- 4Code the sweep. Two while loops and a copy. Say why the overlap test is start ≤ end.
- 5Test out loud. Run the empty list, the touching ends and the swallow-everything case before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?