Given a set of non-overlapping intervals intervals
where intervals[i] = [start_i, end_i]
, insert a new interval newInterval = [start, end]
into intervals
such that intervals
is still sorted in ascending order by start and intervals
still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return the intervals after the insertion.
Example:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
intervals
guaranteed to be sorted by their start values initially?
newInterval
overlap with multiple intervals in intervals
?
newInterval
does not overlap with any of the intervals?
newInterval
should simply be inserted in its correct position to maintain the sorted order.intervals
and:
newInterval
starts directly to the result.newInterval
, updating the newInterval
to the merged interval’s boundaries.newInterval
ends to the result.newInterval
has not been added yet, add it to the result.intervals
list. This is because each interval is processed exactly once.#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> result;
int i = 0;
int n = intervals.size();
// Add all intervals that end before newInterval starts
while (i < n && intervals[i][1] < newInterval[0]) {
result.push_back(intervals[i]);
i++;
}
// Merge all overlapping intervals with newInterval
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = min(newInterval[0], intervals[i][0]);
newInterval[1] = max(newInterval[1], intervals[i][1]);
i++;
}
result.push_back(newInterval);
// Add all remaining intervals after newInterval
while (i < n) {
result.push_back(intervals[i]);
i++;
}
return result;
}
This solution handles the insertion of the new interval by maintaining the sorted order and merging overlapping intervals into a single, unified interval. The result is a list of non-overlapping intervals sorted by their start times.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?