Insert and Merge Interval into Sorted Collection
Greedy & IntervalsAuto-graded · 23 test casesLast updated
Incorporate a target range into an already sorted list of disjoint closed intervals, merging any overlapping or adjacent spans in linear time.
Given a list of disjoint, closed integer intervals intervals sorted in ascending order by their start points, and a single interval new_interval, insert new_interval into the collection.
If adding new_interval causes any ranges to overlap or touch, combine them into a single merged interval. Return the resulting list of intervals, which must remain sorted by start point and contain no overlapping ranges.
Two closed intervals $[a, b]$ and $[c, d]$ are considered touching (and thus must be merged) if they share a boundary, i.e., when $c \le b$ and $a \le d$.
Constraints
0 <= len(intervals) <= 10^4len(intervals[i]) == 2len(new_interval) == 2-10^9 <= intervals[i][0] <= intervals[i][1] <= 10^9-10^9 <= new_interval[0] <= new_interval[1] <= 10^9intervalsis sorted by start point in non-decreasing order.intervalscontains no overlapping ranges prior to insertion.
Examples
Example 1
Input: insert_interval([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8])
Output: [[1, 2], [3, 10], [12, 16]]
Example 2
Input: insert_interval([], [5, 7])
Output: [[5, 7]]
Example 3
Input: insert_interval([[1, 3], [6, 9]], [2, 5])
Output: [[1, 5], [6, 9]]
Example 4
Input: insert_interval([[3, 5], [7, 9]], [1, 2])
Output: [[1, 2], [3, 5], [7, 9]]
Hints
Hint 1
Because the input list is already sorted and disjoint, you can process elements linearly in a single pass without re-sorting.
Hint 2
Divide the existing intervals into three groups relative to the insertion span: those entirely before it, those that overlap or touch it, and those entirely after it.
Hint 3
Maintain a single dynamic range `[start, end]` initialized to `new_interval`. As you iterate through overlapping intervals, update `start = min(start, cur_start)` and `end = max(end, cur_end)`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since the original sequence of intervals is already sorted and mutually disjoint, we do not need to append the new interval and re-sort the entire list—doing so would take $O(n \log n)$ time. Instead, we can achieve $O(n)$ time complexity by making a single linear pass over the input.
Every existing interval falls into one of three sequential categories relative to new_interval = [start, end]:
- Preceding intervals: Intervals that end strictly before
start(i.e.,interval[1] < start). These cannot overlap withnew_intervalor any subsequent intervals, so they are appended directly to the output. - Overlapping or adjacent intervals: Intervals whose start point is less than or equal to the current
end(i.e.,interval[0] <= end). We absorb each such interval intonew_intervalby updatingstart = min(start, interval[0])andend = max(end, interval[1]). - Succeeding intervals: Intervals that start strictly after the newly merged
end. These are appended directly to the output without modification.
After completing step 1 and step 2, we append the fully updated [start, end] to our result before proceeding to step 3.
Complexity
- Time Complexity: $\mathcal{O}(n)$, where $n$ is the number of intervals in the input list. Each interval is processed at most once.
- Space Complexity: $\mathcal{O}(n)$ to construct and return the new list of merged intervals.
from typing import List
def insert_interval(intervals: List[List[int]], new_interval: List[int]) -> List[List[int]]:
result = []
i = 0
n = len(intervals)
start, end = new_interval
# Add all intervals that end strictly before the new interval starts
while i < n and intervals[i][1] < start:
result.append(intervals[i][:])
i += 1
# Merge all overlapping or touching intervals with the new interval
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])
# Add remaining intervals that start strictly after the merged block ends
while i < n:
result.append(intervals[i][:])
i += 1
return result