
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Covered Intervals in C++
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
- if stack is empty or a[i] and stack top interval is intersecting,
- return size of the st.
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool intersect(vector <int>& a, vector <int>& b){ return (b[0] <= a[0] && b[1] >= a[1]) || (a[0] <= b[0] && a[1] >= b[1]); } static bool cmp(vector <int> a, vector <int> b){ return a[1] < b[1]; } void printVector(vector < vector <int> > a){ for(int i = 0; i < a.size(); i++){ cout << a[i][0] << " " << a[i][1] << endl; } cout << endl; } int removeCoveredIntervals(vector<vector<int>>& a) { sort(a.begin(), a.end(), cmp); 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(); } }; main(){ vector<vector<int>> v = {{1,4},{3,6},{2,8}}; Solution ob; cout << (ob.removeCoveredIntervals(v)); }
Input
[[1,4],[3,6],[2,8]]
Output
2
Advertisements