Insert Interval Algorithm
The Insert Interval Algorithm is an efficient approach for merging and inserting new intervals into a pre-existing list of non-overlapping, sorted intervals. This algorithm is particularly useful in scenarios where the intervals represent a range of values or time periods, and we need to incorporate an additional interval into the list while maintaining the sorted and non-overlapping nature of the intervals. The primary goal of this algorithm is to simplify the list by merging any overlapping intervals and ensuring that the newly inserted interval is placed in the correct position according to its range.
The algorithm works by iterating through the existing list of intervals, comparing the new interval to each existing interval, and updating the intervals accordingly. If the new interval does not overlap with the current interval and its start value is greater than the current interval's end value, we know that the new interval should be placed after the current interval. Conversely, if the new interval does not overlap with the current interval and its end value is less than the current interval's start value, we know that the new interval should be placed before the current interval. However, if the new interval overlaps with the current interval, we update the new interval's start and end values to encompass the range of both overlapping intervals. Once the iteration is completed, the new interval is inserted into the list at the appropriate position. This insertion process ensures that the final list of intervals remains sorted and non-overlapping, while also accommodating the new interval.
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<Interval> merged_interval;
bool has_inserted = false;
int new_start = newInterval.start;
int new_end = newInterval.end;
for (int i = 0; i < intervals.size(); i++) {
if (intervals[i].start <= new_end && new_start <= intervals[i].end) {
new_start = min(new_start, intervals[i].start);
new_end = max(new_end, intervals[i].end);
}
else {
if (!has_inserted && new_end < intervals[i].start) {
has_inserted = true;
merged_interval.push_back(Interval(new_start, new_end));
}
merged_interval.push_back(intervals[i]);
}
}
if (!has_inserted)
merged_interval.push_back(Interval(new_start, new_end));
return merged_interval;
}
};