Problem overview
The method insert receives a vector intervals of [start, end] pairs that is already sorted by start and has no overlapping or touching pairs, plus one more interval, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result: still sorted, still without overlaps. Intervals that only touch, like [1,4] and [4,5], count as overlapping and merge into [1,5].
With intervals = [[1,3],[6,9]] and newInterval = [2,5] the answer is [[1,5],[6,9]]. With intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]] and newInterval = [4,8] it is [[1,2],[3,10],[12,16]]: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8. With no intervals, the answer holds just the new one. The expected time is O(n).
Approach: before, overlapping, after
Because the input is sorted and free of overlaps, no sorting is needed. Every interval falls into exactly one of three groups, and the groups come in this order:
- Intervals that end before the new one starts. They go into the answer unchanged.
- Intervals that overlap the new one. They all merge with it into one interval, which only ever grows: an earlier start, a later end.
- Intervals that start after the merged interval ends. They also go in unchanged.
One index i walks through intervals once. Each of three loops picks up where the previous one stopped, so the whole thing is one pass. Compared with the Merge Intervals idea of sorting everything first, this problem saves the O(n log n) sort, because the order is given.
Step by step
- Declare
result, avector<vector<int>>that will hold the answer. - Store the count and the index.
nisintervals.size()andistarts at 0. - Part one, the loop. While
i < nandintervals[i][1] < newInterval[0], the interval ends before the new one begins. The checki < ncomes first, so that&&stops before reading past the end. The comparison is strict: an interval ending exactly atnewInterval[0]touches it and must be merged. - Part one, the body.
push_back(intervals[i])and increasei. - Part two, the growing interval. Declare
startasnewInterval[0]andendasnewInterval[1]. - Part two, the loop. While
i < nandintervals[i][0] <= end, the interval starts no later than the growing one ends. Every interval that is left ends at or afternewInterval[0], so this is exactly the overlap test. It uses<=because an interval starting exactly atendtouches it. Since the input is sorted, once one interval starts afterend, all the rest do too. - Widen the start with
min(start, intervals[i][0]). Only the first overlapping interval can start earlier than the new one. - Widen the end with
max(end, intervals[i][1]). Keeping the larger end matters when an interval lies completely inside the growing one, like[4,5]inside[3,9]. - Move on with
i++, or the loop would look at the same interval forever. - Push the merged interval
{start, end}ontoresult. It goes after part one and before part three, so the order by start is kept. - Part three, the loop. While
i < n, every interval left starts afterend, so none can overlap the merged one. - Part three, the body. As in part one,
push_back(intervals[i])andi++. - Return
result.
The solution in C++
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> result;
int n = intervals.size();
int i = 0;
while (i < n && intervals[i][1] < newInterval[0]) {
result.push_back(intervals[i]);
i++;
}
int start = newInterval[0], end = newInterval[1];
while (i < n && intervals[i][0] <= end) {
start = min(start, intervals[i][0]);
end = max(end, intervals[i][1]);
i++;
}
result.push_back({start, end});
while (i < n) {
result.push_back(intervals[i]);
i++;
}
return result;
}
};
For the second example, the first loop keeps [1,2], which ends at 2, before 4. The second loop then absorbs [3,5] (the growing interval becomes [3,8]), [6,7] (still [3,8]) and [8,10] (now [3,10]). It stops at [12,16], which starts after 10. The merged [3,10] is pushed, then the third loop keeps [12,16]. The result is [[1,2],[3,10],[12,16]].
The C++ details:
int n = intervals.size()converts the unsigned size toint, so the comparisonsi < nare between two signed numbers.- Short-circuit
&&. Ini < n && intervals[i][1] < ..., the right side is evaluated only wheni < nholds. Readingintervals[i]withi == nis undefined behaviour in C++, not a clean error. push_back(intervals[i])copies that inner vector intoresult, andpush_back({start, end})builds a new one from the braces.int start = newInterval[0], end = newInterval[1];declares two variables of the same type in one statement.- The inputs are not changed. Unlike the sorting lessons, this function only reads
intervalsandnewIntervaland builds a new vector.
Complexity
Time: O(n). The index i only moves forward and the three loops together visit each interval once, with constant work each.
Space: O(n) for result, which holds up to n + 1 intervals.
Edge cases and common mistakes
- No intervals.
[]with[5,7]gives[[5,7]]: all three loops are skipped except the push in the middle. - The new interval fits between two intervals.
[[1,2],[8,9]]with[4,5]gives[[1,2],[4,5],[8,9]]. The second loop never runs. - The new interval comes first or last.
[[4,5]]with[1,2]gives[[1,2],[4,5]], and with[7,8]gives[[4,5],[7,8]]. - The new interval bridges two intervals.
[[1,2],[3,4]]with[2,3]gives[[1,4]]. - The new interval lies inside an existing one.
[[3,9]]with[4,5]gives[[3,9]]. Usingmaxandminkeeps the wider bounds. - Touching on the right with
<instead of<=in part two. For[[1,2],[5,6]]with[3,5], the interval[5,6]touches the new one at 5. A strict comparison leaves them separate and returns[[1,2],[3,5],[5,6]]instead of merging. - Checking
intervals[i]beforei < n. This reads one element past the end once the first loop reaches the last interval.
Testing
[[1,3],[6,9]]with[2,5]gives[[1,5],[6,9]].[[1,2],[3,5],[6,7],[8,10],[12,16]]with[4,8]gives[[1,2],[3,10],[12,16]].[]with[5,7]gives[[5,7]].[[1,2],[8,9]]with[4,5]gives[[1,2],[4,5],[8,9]].[[1,2],[3,4]]with[2,3]gives[[1,4]].[[1,5]]with[0,0]gives[[0,0],[1,5]].
