
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
Check If Any Two Intervals Overlap 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
Advertisements