Find Intersection of all Intervals | C ++ implementation of the approach ; Function to print the intersection ; First interval ; Check rest of the intervals and find the intersection ; If no intersection exists ; Else update the intersection ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findIntersection ( int intervals [ ] [ 2 ] , int N ) { int l = intervals [ 0 ] [ 0 ] ; int r = intervals [ 0 ] [ 1 ] ; for ( int i = 1 ; i < N ; i ++ ) { if ( intervals [ i ] [ 0 ] > r intervals [ i ] [ 1 ] < l ) { cout << -1 ; return ; } else { l = max ( l , intervals [ i ] [ 0 ] ) ; r = min ( r , intervals [ i ] [ 1 ] ) ; } } cout << " [ " << l << " , ▁ " << r << " ] " ; } int main ( ) { int intervals [ ] [ 2 ] = { { 1 , 6 } , { 2 , 8 } , { 3 , 10 } , { 5 , 8 } } ; int N = sizeof ( intervals ) / sizeof ( intervals [ 0 ] ) ; findIntersection ( intervals , N ) ; }