text: Given a string and an integer k , find the kth sub | 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: function Printksubstring ( str , n , k ) { let total = parseInt ( ( n * ( n + 1 ) ) / 2 , 10 ) ; if ( k > total ) { document . write ( " " + " " ) ; return ; } let substring = new Array ( n + 1 ) ; substring [ 0 ] = 0 ; let temp = n ; for ( let i = 1 ; i <= n ; i ++ ) { substring [ i ] = substring [ i - 1 ] + temp ; temp -- ; } let l = 1 ; let h = n ; let start = 0 ; while ( l <= h ) { let m = parseInt ( ( l + h ) / 2 , 10 ) ; if ( substring [ m ] > k ) { start = m ; h = m - 1 ; } else if ( substring [ m ] < k ) { l = m + 1 ; } else { start = m ; break ; } } let end = n - ( substring [ start ] - k ) ; for ( let i = start - 1 ; i < end ; i ++ ) { document . write ( str [ i ] ) ; } } let str = " " ; let k = 4 ; let n = str . length ; Printksubstring ( str , n , k ) ;