text: Given a string and an integer k , find the kth sub | Java implementation of the approach ; Function to prints kth sub - string ; Total sub - strings possible ; If k is greater than total number of sub - strings ; To store number of sub - strings starting with ith character of the string ; Compute the values ; substring [ i - 1 ] is added to store the cumulative sum ; Binary search to find the starting index of the kth sub - string ; To store the ending index of the kth sub - string ; Print the sub - string ; Driver code
code: class GFG { static void Printksubstring ( String str , int n , int k ) { int total = ( n * ( n + 1 ) ) / 2 ; if ( k > total ) { System . out . printf ( "-1NEW_LINE"); return ; } int substring [ ] = new int [ n + 1 ] ; substring [ 0 ] = 0 ; int temp = n ; for ( int i = 1 ; i <= n ; i ++ ) { substring [ i ] = substring [ i - 1 ] + temp ; temp -- ; } int l = 1 ; int h = n ; int start = 0 ; while ( l <= h ) { int m = ( l + h ) / 2 ; if ( substring [ m ] > k ) { start = m ; h = m - 1 ; } else if ( substring [ m ] < k ) { l = m + 1 ; } else { start = m ; break ; } } int end = n - ( substring [ start ] - k ) ; for ( int i = start - 1 ; i < end ; i ++ ) { System . out . print ( str . charAt ( i ) ) ; } } public static void main ( String [ ] args ) { String str = " abc " ; int k = 4 ; int n = str . length ( ) ; Printksubstring ( str , n , k ) ; } }