Skip to content

Instantly share code, notes, and snippets.

@shubham1710
Created June 15, 2020 02:56
Show Gist options
  • Select an option

  • Save shubham1710/f4284a5b1b5901055b1e8bffd879047a to your computer and use it in GitHub Desktop.

Select an option

Save shubham1710/f4284a5b1b5901055b1e8bffd879047a to your computer and use it in GitHub Desktop.
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
size_t i = 0;
// Left part (no intersection with newInterval)
while (i < intervals.size() && intervals[i][1] < newInterval[0]) {
res.push_back(intervals[i]);
++i;
}
// newInterval part (with or without merge)
while (i < intervals.size() && intervals[i][0] <= newInterval[1]) {
newInterval[0] = min(newInterval[0], intervals[i][0]);
newInterval[1] = max(newInterval[1], intervals[i][1]);
++i;
}
res.push_back(newInterval);
// Right part (no intersection with newInterval)
while (i < intervals.size() && intervals[i][0] > newInterval[1]) {
res.push_back(intervals[i]);
++i;
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment