text: Find smallest range containing elements from k lists | Java program to finds out smallest range that includes elements from each of the given sorted lists . ; array for storing the current index of list i ; This function takes an k sorted lists in the form of 2D array as an argument . It finds out smallest range that includes elements from each of the k lists . ; initializing to 0 index ; ; for maintaining the index of list containing the minimum element ; iterating over all the list ; if every element of list [ i ] is traversed then break the loop ; find minimum value among all the list elements pointing by the ptr [ ] array ; update the index of the list ; find maximum value among all the list elements pointing by the ptr [ ] array ; if any list exhaust we will not get any better answer , so break the while loop ; updating the minrange ; Driver program to test above function
code: class GFG { static final int N = 5 ; static int ptr [ ] = new int [ 501 ] ; static void findSmallestRange ( int arr [ ] [ ] , int n , int k ) { int i , minval , maxval , minrange , minel = 0 , maxel = 0 , flag , minind ; for ( i = 0 ; i <= k ; i ++ ) { ptr [ i ] = 0 ; } minrange = Integer . MAX_VALUE ; while ( true ) { minind = - 1 ; minval = Integer . MAX_VALUE ; maxval = Integer . MIN_VALUE ; flag = 0 ; for ( i = 0 ; i < k ; i ++ ) { if ( ptr [ i ] == n ) { flag = 1 ; break ; } if ( ptr [ i ] < n && arr [ i ] [ ptr [ i ] ] < minval ) { minind = i ; minval = arr [ i ] [ ptr [ i ] ] ; } if ( ptr [ i ] < n && arr [ i ] [ ptr [ i ] ] > maxval ) { maxval = arr [ i ] [ ptr [ i ] ] ; } } if ( flag == 1 ) { break ; } ptr [ minind ] ++ ; if ( ( maxval - minval ) < minrange ) { minel = minval ; maxel = maxval ; minrange = maxel - minel ; } } System . out . printf ( "The smallest range is [%d, %d]NEW_LINE", minel, maxel); } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 4 , 7 , 9 , 12 , 15 } , { 0 , 8 , 10 , 14 , 20 } , { 6 , 12 , 16 , 30 , 50 } } ; int k = arr . length ; findSmallestRange ( arr , N , k ) ; } }