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
def lexicographicallyMaximum ( S , N ) : NEW_LINE INDENT M = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if S [ i ] in M : NEW_LINE M [ S [ i ] ] += 1 NEW_LINE else : NEW_LINE INDENT M [ S [ i ] ] = 1 NEW_LINE DEDENT DEDENT V = [ ] NEW_LINE for i in range ( ord ( ' a ' ) , ord ( ' a ' ) + min ( N , 25 ) ) : NEW_LINE INDENT if i not in M : NEW_LINE INDENT V . append ( chr ( i ) ) NEW_LINE DEDENT DEDENT j = len ( V ) - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( ord ( S [ i ] ) >= ( ord ( ' a ' ) + min ( N , 25 ) ) or ( S [ i ] in M and M [ S [ i ] ] > 1 ) ) : NEW_LINE INDENT if ( ord ( V [ j ] ) < ord ( S [ i ] ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT M [ S [ i ] ] -= 1 NEW_LINE S = S [ 0 : i ] + V [ j ] + S [ ( i + 1 ) : ] NEW_LINE j -= 1 NEW_LINE DEDENT if ( j < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT l = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( l > j ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( ord ( S [ i ] ) >= ( ord ( ' a ' ) + min ( N , 25 ) ) or S [ i ] in M and M [ S [ i ] ] > 1 ) : NEW_LINE INDENT M [ S [ i ] ] -= 1 NEW_LINE S = S [ 0 : i ] + V [ l ] + S [ ( i + 1 ) : ] NEW_LINE l += 1 NEW_LINE DEDENT DEDENT s = list ( S ) NEW_LINE s [ len ( s ) - 1 ] = ' d ' NEW_LINE S = " " . join ( s ) NEW_LINE return S NEW_LINE DEDENT S = " abccefghh " NEW_LINE N = len ( S ) NEW_LINE print ( lexicographicallyMaximum ( S , N ) ) NEW_LINE