# Insert Interval in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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<b;
}
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);
int index = 1;
bool done = false;
while(index<n){
int last = ans.size()-1;
if(max(ans[last],ans[last])<min(intervals[index],intervals[i ndex])){
ans.push_back(intervals[index]);
} else {
ans[last] = min(ans[last],intervals[index]);
ans[last] = max(ans[last],intervals[index]);
}
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, ],]