

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Check if any two intervals overlap among a given set of intervals in C++
Suppose, we are given a set of intervals that consists of values (time1, time2) where time1 represents the starting time, and time2 represents the ending time of an event. Our task is to check whether any of these intervals overlap any other interval in this set. If any of the intervals overlap, we return the result as True, otherwise we return False.
So, if the input is like [(4,7), (5,11), (7,11), (5,8)] then the output will be True.
To solve this, we will follow these steps −
- sort the list inputArr
- for i in range 1 to size of inputArr, do
- if inputArr [i - 1].time2 > inputArr[i].time1 then
- return True
- return False
- if inputArr [i - 1].time2 > inputArr[i].time1 then
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class IntervalClass { public: int time1, time2; }; bool compare(IntervalClass inst1, IntervalClass inst2){ return (inst1.time1 < inst2.time1) ? true : false; } bool solve(vector<IntervalClass> &inputArr){ int size = inputArr.size(); sort(inputArr.begin(), inputArr.end(), compare); for (int i = 1; i < size; i++) if (inputArr[i - 1].time2 > inputArr[i].time1) return true; return false; } int main(){ vector<IntervalClass> inputArr = {{4,7},{5,11},{7,11},{5,8}}; int size = sizeof(inputArr) / sizeof(inputArr[0]); cout << solve(inputArr); }
Input
{{4,7},{5,11},{7,11},{5,8}}
Output
1
- Related Questions & Answers
- Python Pandas IntervalIndex - Check if Intervals that share closed endpoints overlap
- Python Pandas IntervalArray - Check Intervals that share closed endpoints overlap or not
- Python Pandas IntervalIndex - Check if Intervals that only have an open endpoint in common overlap or not
- Python Pandas - Check if the IntervalIndex has overlapping intervals
- Python Pandas - Check elementwise if the Intervals contain the value
- Python Pandas IntervalArray - Check Intervals that only have an open endpoint in common overlap or not
- Python Pandas - Check if the Intervals in the IntervalArray is empty
- Set scroll view with intervals in JavaScript
- Minimum Size of Two Non-Overlapping Intervals in C++
- Merge Intervals in Python
- Python Pandas - Check elementwise if the Intervals in the IntervalIndex contain the value
- Count the number of intervals in which a given value lies in C++
- Check elementwise if the Intervals in the IntervalIndex contain the value in Python Pandas
- Program to count number of intervals that is totally contained inside other intervals in Python
- Maximal Disjoint Intervals in C++
Advertisements