# Check if any two intervals overlap among a given set of intervals in C++

C++Server Side ProgrammingProgramming

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

Let us see the following implementation to get better understanding −

## Example

Live Demo

#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);
cout << solve(inputArr);
}

## Input

{{4,7},{5,11},{7,11},{5,8}}

## Output

1