Find Intersection of all Intervals | Java 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
import java . io . * ; class GFG { static void findIntersection ( int intervals [ ] [ ] , 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 ) { System . out . println ( - 1 ) ; return ; } else { l = Math . max ( l , intervals [ i ] [ 0 ] ) ; r = Math . min ( r , intervals [ i ] [ 1 ] ) ; } } System . out . println ( " [ " + l + " , ▁ " + r + " ] " ) ; } public static void main ( String [ ] args ) { int intervals [ ] [ ] = { { 1 , 6 } , { 2 , 8 } , { 3 , 10 } , { 5 , 8 } } ; int N = intervals . length ; findIntersection ( intervals , N ) ; } }