Insert Interval in C++


Suppose we have a set of non-overlapping intervals; we have to insert a new interval into the intervals. We can merge if necessary. So if the input is like − [[1,4],[6,9]], and new interval is [2,5], then the output will be [[1,5],[6,9]].

To solve this, we will follow these steps −

  • Insert new interval at the end of the previous interval list

  • sort the interval list based on the initial time of the intervals, n := number of intervals

  • create one array called ans, insert first interval into ans

  • index := 1

  • while index < n,

    • last := size of ans – 1

    • if max of ans[last, 0] and ans[last, 1] < min of intervals[index, 0], intervals[index, 1], then insert intervals[index] into ans

    • otherwise

      • set ans[last, 0] := min of ans [last, 0], intervals[index, 0]

      • set ans[last, 1] := min of ans [last, 1], intervals[index, 1]

    • increase index by 1

  • return ans

Example

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   static bool cmp(vector <int> a, vector <int> b){
      return a[0]<b[0];
   }
   vector<vector <int>>insert(vector<vector <int> >& intervals, vector <int>& newInterval) {
      intervals.push_back(newInterval);
      sort(intervals.begin(),intervals.end(),cmp);
      int n = intervals.size();
      vector <vector <int>> ans;
      ans.push_back(intervals[0]);
      int index = 1;
      bool done = false;
      while(index<n){
         int last = ans.size()-1;
         if(max(ans[last][0],ans[last][1])<min(intervals[index][0],intervals[i ndex][1])){
            ans.push_back(intervals[index]);
         } else {
            ans[last][0] = min(ans[last][0],intervals[index][0]);
            ans[last][1] = max(ans[last][1],intervals[index][1]);
         }
         index++;
      }
      return ans;
   }
};
main(){
   vector<vector<int>> v = {{1,4},{6,9}};
   vector<int> v1 = {2,5};
   Solution ob;
   print_vector(ob.insert(v, v1));
}

Input

[[1,4],[6,9]]
[2,5]

Output

[[1, 5, ],[6, 9, ],]

Updated on: 26-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements