# Remove 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

Best Seller

66 Lectures 5.5 hours

Suppose we have a sorted list of disjoint intervals, each interval intervals[i] = [a, b] represents the set of numbers x such that a <= x < b. We have to remove the intersections between any interval in intervals and the interval toBeRemoved. Finally, we have to find the sorted list of intervals after all such removals. So if the input is like − [[0,2], [3,4],[5,7]], and toBeRemoved := [1, 6], so the output will be [[0, 2], [6,7]].

To solve this, we will follow these steps −

• Define a method called manipulate2(), this will take matrix a and an array y
• x := last row of matrix a, then delete last row from a
• z := x
• x[0] := y[1], z[1] := y[0]
• if z[0] − z[1], then insert z into a
• if x[0] − x[1], then insert x into a
• The main method will take matrix in and an array t
• define a matrix ans, and n := number of rows in matrix in
• for i in range 0 to n –
• insert in[i] into ans
• a := last row of a, b := t
• if a[0] > b[0], then swap a and b
• if a and b are intersecting, then call manipulate2(ans, t)
• return ans

## Example(C++)

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

Live Demo

#include <bits/stdc++.h>
using namespace std;
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:
bool isIntersect(vector <int> a, vector <int> b){
return max(a[0], a[1]) >= min(b[0], b[1]);
}
void manipulate2(vector < vector <int> > &a, vector <int> y){
vector <int> x = a.back();
a.pop_back();
vector <int> z = x;
x[0] = y[1];
z[1] = y[0];
if(z[0] < z[1])a.push_back(z);
if(x[0] < x[1])a.push_back(x);
}
vector<vector<int>> removeInterval(vector<vector<int>>& in, vector<int>& t) {
vector < vector <int> > ans;
int n = in.size();
for(int i = 0; i < n; i++){
ans.push_back(in[i]);
vector <int> a;
vector <int> b;
a = ans.back();
b = t;
if(a[0]>b[0])swap(a, b);
if(isIntersect(a, b)){
manipulate2(ans, t);
}
}
return ans;
}
};
main(){
vector<int> v2 = {1,6};
vector<vector<int>> v1 = {{0,2},{3,4},{5,7}};
Solution ob;
print_vector(ob.removeInterval(v1, v2));
}

## Input

[[0,2],[3,4],[5,7]]
[1,6]

## Output

[[0, 1, ],[6, 7, ],]
Updated on 30-Apr-2020 09:47:27