Find a pair of intersecting ranges from a given array | Java program for the above approach ; Store ranges and their corresponding array indices ; Function to find a pair of intersecting ranges ; Stores ending point of every range ; Stores the maximum ending point obtained ; Iterate from 0 to N - 1 ; Starting point of the current range ; End point of the current range ; Push pairs into tup ; Sort the tup vector sort ( tup . begin ( ) , tup . end ( ) ) ; ; Iterate over the ranges ; If starting points are equal ; Print the indices of the intersecting ranges ; If no such pair of segments exist ; Driver Code ; Given N ; Given 2d ranges [ ] [ ] array ; Function call
import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; class GFG { static ArrayList < int [ ] > tup = new ArrayList < > ( ) ; static void findIntersectingRange ( int N , int ranges [ ] [ ] ) { int curr ; int currPos ; for ( int i = 0 ; i < N ; i ++ ) { int x , y ; x = ranges [ i ] [ 0 ] ; y = ranges [ i ] [ 1 ] ; int [ ] arr = { x , y , i + 1 } ; tup . add ( arr ) ; } Collections . sort ( tup , new Comparator < int [ ] > ( ) { public int compare ( int [ ] a , int [ ] b ) { if ( a [ 0 ] == b [ 0 ] ) { if ( a [ 1 ] == b [ 1 ] ) { return a [ 2 ] - b [ 2 ] ; } else { return a [ 1 ] - b [ 1 ] ; } } return a [ 0 ] - b [ 0 ] ; } } ) ; curr = tup . get ( 0 ) [ 1 ] ; currPos = tup . get ( 0 ) [ 2 ] ; for ( int i = 1 ; i < N ; i ++ ) { int Q = tup . get ( i - 1 ) [ 0 ] ; int R = tup . get ( i ) [ 0 ] ; if ( Q == R ) { if ( tup . get ( i - 1 ) [ 1 ] < tup . get ( i ) [ 1 ] ) System . out . print ( tup . get ( i - 1 ) [ 2 ] + " ▁ " + tup . get ( i ) [ 2 ] ) ; else System . out . print ( tup . get ( i ) [ 2 ] + " ▁ " + tup . get ( i - 1 ) [ 2 ] ) ; return ; } int T = tup . get ( i ) [ 1 ] ; if ( T <= curr ) { System . out . print ( tup . get ( i ) [ 2 ] + " ▁ " + currPos ) ; return ; } else { curr = T ; currPos = tup . get ( i ) [ 2 ] ; } } System . out . print ( " - 1 ▁ - 1" ) ; } public static void main ( String [ ] args ) { int N = 5 ; int ranges [ ] [ ] = { { 1 , 5 } , { 2 , 10 } , { 3 , 10 } , { 2 , 2 } , { 2 , 15 } } ; findIntersectingRange ( N , ranges ) ; } }