Insert Interval
Insert Interval is LeetCode 57 (Medium). You get intervals, a list of [start, end] pairs sorted by start, where no two pairs overlap, and one more pair, newInterval. Put the new pair in, merge any pairs that now overlap, and return a list that is again sorted and overlap-free.
- Pairs that share only an endpoint, such as
[1, 3]and[3, 5], count as overlapping. - The list may be empty and holds up to 10⁴ pairs.
- 0 <= intervals.length <= 10⁴
- intervals[i].length == 2
- 0 <= startᵢ <= endᵢ <= 10⁵
- intervals is sorted by startᵢ in ascending order
- newInterval.length == 2
- 0 <= start <= end <= 10⁵
Intuition
Because the list is sorted and its pairs never overlap, the pairs that touch the new interval cannot be scattered. They sit in one unbroken run: every pair before the run ends too early, and every pair after it starts too late. So one left-to-right walk splits the list into three stretches:
- Before: the pair ends before the new interval starts, so it is copied as it is.
- Touching: the pair starts no later than the new interval's current end, so it is swallowed and the new interval stretches to cover both.
- After: everything left over, copied as it is once the stretched interval has been placed.
A list that is already sorted and overlap-free, plus one change to it, points to a single linear walk instead of a fresh sort.
Approach
Before reading on, take [[1, 2], [3, 5], [6, 7], [8, 10]] and the new pair [4, 8]. Mark which pairs the new one reaches. Are they next to each other? What bounds do they merge into?
Copy the pairs that end too early
Walk from the front while the current pair ends before newInterval starts, and append each one to the answer. Such a pair cannot reach the new interval, and since the list is sorted, no pair before it can either.
Swallow every pair that touches
Keep lo and hi, the bounds of the growing interval. While the next pair starts at or before hi, set lo to the smaller start and hi to the larger end. Testing against the growing hi lets one long interval swallow several pairs in a row.
Place the merged interval once
When a pair starts after hi, or the list runs out, append [lo, hi]. Adding it only now means it goes in at its final size and in its sorted spot.
Copy the rest
Every pair still waiting starts after hi. They are already sorted and apart from each other, so append them unchanged.
Why the walk never looks back
Once a pair starts after hi, every later pair starts later still, so none of them can reach back to the merged interval. That is why one pass is enough and why the answer stays sorted without a sort.
Code in Python, C++ and Java
Common pitfalls
Leaving pairs that share an endpoint apart
while i < n and intervals[i][0] < hi:
while i < n and intervals[i][0] <= hi:
A shared endpoint counts as overlap. On [[1, 3], [5, 7]] with [2, 5], the strict test stops at [5, 7] and returns [[1, 5], [5, 7]] instead of [[1, 7]].
Stretching only the right end
hi = max(hi, intervals[i][1])
lo = min(lo, intervals[i][0]) hi = max(hi, intervals[i][1])
The first pair swallowed can start before the new interval does. With [[3, 5]] and [4, 8] the answer is [[3, 8]], but moving only hi returns [[4, 8]].
Edge cases
[] with [5, 7]Both copy loops and the swallow loop do nothing, so the answer is just [[5, 7]].
[[3, 4]] with [1, 2]Nothing is copied first and nothing is swallowed, so [1, 2] lands at the front.
[[1, 9]] with [3, 4][1, 9] is swallowed, lo and hi become 1 and 9, and the list comes back as it was.
Complexity
lo, hi and the index are kept.Insert Interval FAQ
Can I add the new pair, sort, and merge instead?
Yes, and it gives the right answer: it is the Merge Intervals method (LeetCode 56). It costs O(n log n) for the sort, which redoes an ordering the input already gives you for free.
Does binary search make it faster?
Binary search finds where the touching run starts and ends in O(log n). The answer is still a list of up to n + 1 pairs, though, so building it costs O(n) either way. It only helps when the list lives in a structure that can cut out a run cheaply, such as a balanced tree.