Lexicographically smallest string formed by appending a character from the first K characters of a given string | Function to find the new string thus formed by removing characters ; new string ; Remove characters until the string is empty ; Traverse to find the smallest character in the first k characters ; append the smallest character ; removing the lexicographically smallest character from the string ; Driver code
< ? php function newString ( $ s , $ k ) { $ X = " " ; while ( strlen ( $ s ) > 0 ) { $ temp = $ s [ 0 ] ; for ( $ i = 1 ; $ i < $ k && $ i < strlen ( $ s ) ; $ i ++ ) { if ( $ s [ $ i ] < $ temp ) { $ temp = $ s [ $ i ] ; } } $ X = $ X . $ temp ; for ( $ i = 0 ; $ i < $ k ; $ i ++ ) { if ( $ s [ $ i ] == $ temp ) { $ s = substr ( $ s , 0 , $ i ) . substr ( $ s , $ i + 1 , strlen ( $ s ) ) ; break ; } } } return $ X ; } $ s = " gaurang " ; $ k = 3 ; echo ( newString ( $ s , $ k ) ) ; ? >