# Remove Covered Intervals in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of intervals, we have to remove all intervals that are covered by another interval in the list. Here Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d. So after doing so, we have to return the number of remaining intervals. If the input is like [[1,4],[3,6],[2,8]], then the output will be 2, The interval [3,6] is covered by [1,4] and [2,8], so the output will be 2.

To solve this, we will follow these steps −

• Sort the interval list based on the ending time
• define a stack st
• for i in range 0 to size of a – 1
• if stack is empty or a[i] and stack top interval is intersecting,
• insert a[i] into st
• otherwise
• temp := a[i]
• while st is not not empty and temp and stack top interval is intersecting
• pop from stack
• insert temp into st
• return size of the st.

## Example

Let us see the following implementation to get better understanding −

class Solution {
public:
bool intersect(vector <int>& a, vector <int>& b){
return (b <= a && b >= a) || (a <= b && a >= b);
}
static bool cmp(vector <int> a, vector <int> b){
return a < b;
}
void printVector(vector < vector <int> > a){
for(int i = 0; i < a.size(); i++){
cout << a[i] << " " << a[i] << endl;
}
cout << endl;
}
int removeCoveredIntervals(vector<vector<int>>& a) {
sort(a.begin(), a.end(), cmp);
//printVector(a);
stack < vector <int> > st;
for(int i = 0; i < a.size(); i++){
if(st.empty() || !intersect(a[i], st.top())){
st.push(a[i]);
} else {
vector <int> temp = a[i];
while(!st.empty() && intersect(temp, st.top())){
st.pop();
}
st.push(temp);
}
}
return st.size();
}
};

## Input

[[1,4],[3,6],[2,8]]

## Output

2