Lexicographically next greater string using same character set | function to print output ; to store unique characters of the string ; to check uniqueness ; if mp [ s [ i ] ] = 0 then it is first time ; sort the unique characters ; simply add n - k smallest characters ; return ; end the program ; searching the first character left of index k and not equal to greatest character of the string ; finding the just next greater character than s [ i ] ; suffix with smallest character ; if we reach here then all indices to the left of k had the greatest character ; Driver code ; Function call
function lexoString ( s , k ) { var n = s . length ; var v = [ ] ; var mp = { } ; for ( var i = 0 ; i < s . length ; i ++ ) { if ( ! mp . hasOwnProperty ( s [ i ] ) ) { mp [ s [ i ] ] = 1 ; v . push ( s [ i ] ) ; } } v . sort ( ( a , b ) => a - b ) ; if ( k > n ) { document . write ( s . join ( " " ) ) ; for ( var i = n ; i < k ; i ++ ) { document . write ( v [ 0 ] ) ; } } for ( var i = k - 1 ; i >= 0 ; i -- ) { if ( s [ i ] !== v [ v . length - 1 ] ) { for ( var j = 0 ; j < i ; j ++ ) { document . write ( s [ j ] ) ; } for ( var j = 0 ; j < v . length ; j ++ ) { if ( v [ j ] > s [ i ] ) { document . write ( v [ j ] ) ; break ; } } for ( var j = i + 1 ; j < k ; j ++ ) { document . write ( v [ 0 ] ) ; } return ; } } document . write ( " " + " " + k + " " ) ; } var s = " " ; var k = 3 ; lexoString ( s . split ( " " ) , k ) ;