✅Merge Intervals
Logic
For every
intervalinintervalsIf it comes before the
newIntervalwith no overlap:current.end < newInterval.startPush
currentinto theresultvector
If
newIntervalcomes before thecurrentinterval with no overlap:current.start > newInterval.endPush
newIntervalinto theresultvectorcurrentis the newnewInterval
If both conditions are false then definitely there has been an overlap
Merge the
currentinterval tonewInterval
In the end,
newIntervalwill be leftPush it into the
resultvector
Code
vector<Interval> Solution::insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> res;
for(Interval test: intervals)
// New Interval comes after Test with no overlap
if(newInterval.start > test.end)
// insert Test
res.push_back(test);
// new interval comes before thest with no overlap
else if(test.start > newInterval.end) {
// insert New Interval
res.push_back(newInterval);
// Put Test into New Interval
newInterval = test;
// any other case of over lap
} else
// merge Test with New Interval
newInterval = Interval(min(test.start, newInterval.start), max(test.end, newInterval.end));
res.push_back(newInterval);
return res;
}Last updated