NeetCode #832LC-57MediumIntervalsBlind 75NC 150NC 250
← Back to All Problems#832 · #57 · Insert Interval(插入区间)
📌 Problem Statement & Constraints
You are given an array of non-overlapping intervals
intervals, sorted by start, and a newInterval. Insert newInterval and merge any overlaps so the result stays non-overlapping and sorted. Return the resulting array. Constraints: 0 <= intervals.length <= 10^4, 0 <= intervals[i][0] <= intervals[i][1] <= 10^5, 0 <= newInterval[0] <= newInterval[1] <= 10^5.💡 Core Algorithmic Approaches
- The intervals are already sorted, so a single linear pass suffices -- no sort is needed.
- First copy every interval that ends before
newIntervalstarts; these are untouched. - Then absorb every interval that starts at or before the current
newIntervalend, wideningnewIntervalto the union. - Append the merged interval, then copy the untouched tail.
💻 Benchmark Python3 Implementation
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
i = 0
n = len(intervals)
while i < n and intervals[i][1] < newInterval[0]:
res.append(intervals[i]) # strictly before, no overlap
i += 1
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
res.append(newInterval)
res.extend(intervals[i:])
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): a single pass over the sorted intervals.
💾 Space Complexity
O(n) for the output (the algorithm uses O(1) extra).
⚠️ Interview Pitfalls & Follow-ups
- Using
<=for the before-test: touching intervals like[1,2]and[2,3]are considered overlapping, so the test must be strictend < newStart. - Sorting the input again: it is already sorted, and sorting would not help the merge.
- Merging only one interval: the new interval can overlap a whole run, which is why the second loop keeps absorbing.
- Forgetting the empty input:
intervalsmay be empty; the loops simply do not execute andnewIntervalis appended alone.