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: < ? php function Printksubstring ( $ str , $ n , $ k ) { $ total = floor ( ( $ n * ( $ n + 1 ) ) / 2 ) ; if ( $ k > $ total ) { printf ( " - 1 STRNEWLINE " ) ; return ; } $ substring = array ( ) ; $ substring [ 0 ] = 0 ; $ temp = $ n ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { $ substring [ $ i ] = $ substring [ $ i - 1 ] + $ temp ; $ temp -- ; } $ l = 1 ; $ h = $ n ; $ start = 0 ; while ( $ l <= $ h ) { $ m = floor ( ( $ l + $ h ) / 2 ) ; if ( $ substring [ $ m ] > $ k ) { $ start = $ m ; $ h = $ m - 1 ; } else if ( $ substring [ $ m ] < $ k ) $ l = $ m + 1 ; else { $ start = $ m ; break ; } } $ end = $ n - ( $ substring [ $ start ] - $ k ) ; for ( $ i = $ start - 1 ; $ i < $ end ; $ i ++ ) print ( $ str [ $ i ] ) ; } $ str = " abc " ; $ k = 4 ; $ n = strlen ( $ str ) ; Printksubstring ( $ str , $ n , $ k ) ; ? >