text: Lexicographically largest string formed in minimum moves by replacing characters of given String | Function to print the lexicographically the largest string obtained in process of obtaining a string containing first N lower case english alphabtes ; Store the frequency of each character ; Traverse the string S ; Stores the characters which are not appearing in S ; Stores the index of the largest character in the array V , that need to be replaced ; Traverse the string , S ; If frequency of S [ i ] is greater than 1 or it is outside the range ; Decrement its frequency by 1 ; Update S [ i ] ; Decrement j by 1 ; Traverse the string , S ; Decrement its frequency by 1 ; Update S [ i ] ; Increment l by 1 ; Return S ; Given Input ; Function Call
code: function lexicographicallyMaximum ( S , N ) { let M = new Map ( ) ; for ( let i = 0 ; i < N ; ++ i ) { if ( M . has ( S [ i ] ) ) M . set ( S [ i ] , M . get ( S [ i ] ) + 1 ) ; else M . set ( S [ i ] , 1 ) ; } let V = [ ] ; for ( let i = ' ' . charCodeAt ( ) ; i < ( ' ' . charCodeAt ( ) + Math . min ( N , 25 ) ) ; ++ i ) { if ( M . has ( String . fromCharCode ( i ) ) == false ) { V . push ( String . fromCharCode ( i ) ) ; } } let j = V . length - 1 ; for ( let i = 0 ; i < N ; ++ i ) { if ( S [ i ] . charCodeAt ( ) >= ( ' ' . charCodeAt ( ) + Math . min ( N , 25 ) ) || ( M . has ( S [ i ] ) && M . get ( S [ i ] ) > 1 ) ) { if ( V [ j ] . charCodeAt ( ) < S [ i ] . charCodeAt ( ) ) continue ; M . set ( S [ i ] , M . get ( S [ i ] ) - 1 ) ; S = S . substr ( 0 , i ) + V [ j ] + S . substr ( i + 1 ) ; j -- ; } if ( j < 0 ) break ; } let l = 0 ; for ( let i = N - 1 ; i >= 0 ; i -- ) { if ( l > j ) break ; if ( S [ i ] . charCodeAt ( ) >= ( ' ' . charCodeAt ( ) + Math . min ( N , 25 ) ) || M . has ( S [ i ] ) && M . get ( S [ i ] ) > 1 ) { M . set ( S [ i ] , M . get ( S [ i ] ) - 1 ) ; S = S . substr ( 0 , i ) + V [ l ] + S . substr ( i + 1 ) ; l ++ ; } } return S ; } let S = " " ; let N = S . length ; document . write ( lexicographicallyMaximum ( S , N ) ) ;