Insert Interval
Problem
You are given an array of non-overlapping intervals intervals where intervals[i] = [start_i, end_i] represents the start and the end time of the ith interval. intervals is initially sorted in ascending order by start_i.
You are given another interval newInterval = [start, end].
Insert newInterval into intervals such that intervals is still sorted in ascending order by start_i and also intervals still does not have any overlapping intervals. You may merge the overlapping intervals if needed.
Return intervals after adding newInterval.
Note: Intervals are non-overlapping if they have no common point. For example, [1,2] and [3,4] are non-overlapping, but [1,2] and [2,3] are overlapping.
Examples
Example 1:
Input: intervals = [[1,3],[4,6]], newInterval = [2,5]
Output: [[1,6]]
Explanation: [2,5] overlaps with [1,3] and [4,6], so all three are merged into [1,6].
Example 2:
Input: intervals = [[1,2],[3,5],[9,10]], newInterval = [6,7]
Output: [[1,2],[3,5],[6,7],[9,10]]
Explanation: [6,7] does not overlap with any existing interval, so it is simply inserted between [3,5] and [9,10].
Constraints
0 <= intervals.length <= 1000newInterval.length == intervals[i].length == 20 <= start <= end <= 1000
You should aim for a solution with O(n) time and O(1) extra space, where n is the size of the input array.
Solution
As we scan forward, we either have the current interval completely to the left, too the right, or straddling.
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
std::vector<std::vector<int>> result;
for (int i = 0; i < intervals.size(); ++i) {
// Current interval is fully left of newInterval
if (intervals[i][1] < newInterval[0]) {
result.push_back(intervals[i]);
}
// Current interval is fully right of newInterval
else if (intervals[i][0] > newInterval[1]) {
result.push_back(newInterval);
std::copy(intervals.begin() + i, intervals.end(), std::back_inserter(result));
return result;
}
// Current interval falls inside range, merge
else {
newInterval[0] = std::min(intervals[i][0], newInterval[0]);
newInterval[1] = std::max(intervals[i][1], newInterval[1]);
}
}
result.push_back(newInterval);
return result;
}
};