Problem Statement:
You are given an interval.
You need to check if any interval completely overlaps other.
Example:
Input: {{1, 3}, {1, 7}, {4, 8}, {2, 5}}
Output: The interval {1, 3} overlaps {1, 7}
Solution Explanation:
Sort the intervals in creasing order of start time.
Iterate through each interval,
If the end time of interval is not more than the end time of the previous interval, meaning, it overlaps. Print the index of the intervals.
If not, print no overlapping intervals.
Time Complexity: O(nlogn)
Space Complexity: O(1)
Code Solution
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
struct Interval
{
int start;
int end;
};
bool compareInterval(Interval i1, Interval i2)
{
return (i1.start < i2.start) ? true : false;
}
bool solution(Interval arr[], int n)
{
sort(arr, arr + n - 1, compareInterval);
for (int i = 1; i < n; i++)
if (arr[i].end <= arr[i - 1].end)
return true;
return false;
}
int main()
{
Interval arr1[] = { { 1, 3 }, { 1, 7 }, { 4, 8 }, { 2, 5 } };
int n1 = sizeof(arr1) / sizeof(arr1[0]);
if (solution(arr1, n1))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
Output
Yes