Find Intersection of all Intervals in C++


Suppose, we have N intervals in the form {L, R}, the L is the starting time, and R is the ending time. We have to find an intersection of all intervals. An intersection is an interval that lies within all of the given intervals. If no such found, return -1. For example, if the intervals are like [{1, 6}, {2, 8}, {3, 10}, {5, 8}, The output interval is {5, 6}

To solve this problem, we will follow these steps −

  • Consider the first interval is the final interval

  • Starting from the second interval, try searching for the intersection. Two cases can be there

    • There exists no intersection between [L1, R1] and [L2, R2] possible only when R1 < L2 or R2 < L1, in such case answer, will be 0

    • There exists no intersection between [L1, R1] and [L2, R2], then required intersection will be {max(L1, L2), min(R1, R2)}

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
class interval{
   public:
      int left, right;
};
void findIntersection(interval intervals[], int N) {
   int l = intervals[0].left;
   int r = intervals[0].right;
   for (int i = 1; i < N; i++) {
      if (intervals[i].left > r || intervals[i].right < l) {
         cout << -1;
         return;
      } else {
         l = max(l, intervals[i].left);
         r = min(r, intervals[i].right);
      }
   }
   cout << "{" << l << ", " << r << "}";
}
int main() {
   interval intervals[] = {{ 1, 6 }, { 2, 8 }, { 3, 10 }, { 5, 8 } };
   int N = sizeof(intervals) / sizeof(intervals[0]);
   findIntersection(intervals, N);
}

Output

{5, 6}

Updated on: 19-Dec-2019

606 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements