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
function newString ( s , k ) { var X = " " ; while ( s . length > 0 ) { var temp = s [ 0 ] ; for ( var i = 1 ; i < k && i < s . length ; i ++ ) { if ( s [ i ] < temp ) { temp = s [ i ] ; } } X = X + temp ; for ( var i = 0 ; i < k ; i ++ ) { if ( s [ i ] === temp ) { s = s . substring ( 0 , i ) + s . substring ( i + 1 ) ; break ; } } } return X ; } var s = " " ; var k = 3 ; document . write ( newString ( s , k ) ) ;