Problem overview
The method insert receives intervals, a list of [start, end] lists that is already sorted by start with no two intervals overlapping or touching, and one more interval, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the resulting list, still sorted and with no overlaps. Intervals that touch, like [1, 4] and [4, 5], share the point 4, so they merge. The list can be empty, and the statement asks for O(n) time.
For intervals = [[1, 3], [6, 9]] and newInterval = [2, 5] the result is [[1, 5], [6, 9]]: [2, 5] overlaps [1, 3], and [6, 9] starts after 5.
Approach: before, overlapping, after
Because the list is sorted and has no overlaps, there is no need to sort again or to compare every pair. The intervals fall into three groups, in this order:
- those that end before
newIntervalstarts: they go into the answer unchanged; - those that overlap it: they all merge with it into a single interval;
- those that start after the merged interval ends: they go in unchanged too.
One index i walks through the list once, and each group's loop picks up where the previous one stopped, so the work is O(n). Merging after a full sort, as in the general merge problem, would cost O(n log n).
A simpler idea is to append newInterval to the list, sort everything and merge as in the general merge problem. That works, but it ignores the guarantee that the input is already in order, and it pays O(n log n) for the sort. The three-group split uses the guarantee: each group is a contiguous run of the list, so a plain index is all the bookkeeping needed. The only subtle part is the boundary between groups, which is decided by the two comparisons: an interval is "before" when it ends strictly earlier than the new start, and it is "overlapping" when it starts no later than the current end.
Step by step
- Create an empty list
result. - Store
len(intervals)innand start an indexiat 0. - Part one: a
whileloop that runs whilei < nandintervals[i][1] < newInterval[0]. Use<: an interval that ends exactly where the new one starts touches it, so it belongs to the merge. Checki < nfirst, becauseandstops there when the intervals run out, beforeintervals[i]is read. - Inside it, append
intervals[i]toresultand doi += 1. - Part two: set
start, end = newInterval[0], newInterval[1], a growing interval that every overlapping interval can only widen. - Loop while
i < nandintervals[i][0] <= end. Every interval left ends at or afternewInterval[0], so it overlaps the growing interval exactly when it starts byend. Use<=, since touching counts. The list is sorted, so once an interval starts afterend, all the rest do too. - Set
starttomin(start, intervals[i][0]). Only the first overlapping interval can start earlier than the new one. - Set
endtomax(end, intervals[i][1]). An interval can lie completely inside the new one, like[4, 5]inside[3, 9], and thenendmust stay 9. - Do
i += 1. Without it the loop would look at the same interval forever. - Append
[start, end]toresultafter the loop. It goes after the part-one intervals and before the part-three ones, which keeps the result sorted. If nothing overlapped,startandendare still the new interval's own values. - Part three: a
whileloop that runs whilei < n. Every interval left starts afterend. - Append
intervals[i]and doi += 1, as in part one. - Return
result.
The solution in Python
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
result = []
n = len(intervals)
i = 0
while i < n and intervals[i][1] < newInterval[0]:
result.append(intervals[i])
i += 1
start, end = newInterval[0], newInterval[1]
while i < n and intervals[i][0] <= end:
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i += 1
result.append([start, end])
while i < n:
result.append(intervals[i])
i += 1
return result
On intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]] and newInterval = [4, 8], part one copies [1, 2] and stops at [3, 5], because 5 is not less than 4. Part two then widens the growing interval: [3, 8] after [3, 5], still [3, 8] after [6, 7], and [3, 10] after [8, 10], which touches it at 8. Part three copies [12, 16]. The result is [[1, 2], [3, 10], [12, 16]].
Python details worth knowing:
andshort-circuits. Ini < n and intervals[i][1] < ...the second test only runs when the first is true, which protects against anIndexErrorat the end of the list.- Tuple assignment.
start, end = newInterval[0], newInterval[1]creates both variables in one line.start, end = newIntervalwould work too for a two-item list. - Shared inner lists. Parts one and three append the input's own inner lists, not copies. If you change an inner list of the result, such as
result[0][0] = 99, the same list inintervalschanges too. The merged interval is a new list. minandmaxreturn the smaller or larger of their arguments.
Complexity
Time: O(n): i only moves forward and each interval is looked at by exactly one loop. Space: O(n) for result, which holds up to n + 1 intervals.
Edge cases and common mistakes
- Empty list.
intervals = []withnewInterval = [5, 7]gives[[5, 7]]: all three loops end at once. - New interval inside an existing one.
[[1, 5]]with[2, 3]gives[[1, 5]]. - New interval first or last.
[[3, 5]]with[0, 1]gives[[0, 1], [3, 5]], and with[7, 8]gives[[3, 5], [7, 8]]. - Touching on both sides.
[[1, 2], [3, 4]]with[2, 3]gives[[1, 4]]. - Fitting in a gap.
[[1, 2], [5, 6]]with[3, 4]gives[[1, 2], [3, 4], [5, 6]]. - Wrong comparison. Writing
<=in the first loop or<in the second leaves touching intervals unmerged. - Forgetting
i += 1. Awhileloop without it never ends.
Testing
[[1, 3], [6, 9]],[2, 5]gives[[1, 5], [6, 9]].[[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]],[4, 8]gives[[1, 2], [3, 10], [12, 16]].[],[5, 7]gives[[5, 7]].[[1, 5]],[2, 3]gives[[1, 5]].[[1, 2], [3, 4]],[2, 3]gives[[1, 4]].
