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

    • 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
#include
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  r || intervals[i].right 

Output

{5, 6}
Updated on: 2019-12-19T09:50:23+05:30

909 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements