Convert given string so that it holds only distinct characters | Function to return the index of the character that has 0 occurrence starting from index i ; If current character has 0 occurrence ; If no character has 0 occurrence ; Function to return the modified string which consists of distinct characters ; String cannot consist of all distinct characters ; Count the occurrences for each of the character ; Index for the first character that hasn 't appeared in the string ; If current character appeared more than once then it has to be replaced with some character that hasn 't occurred yet ; Decrement current character 's occurrence by 1 ; Replace the character ; Update the new character ' s ▁ occurrence ▁ ▁ This ▁ step ▁ can ▁ also ▁ be ▁ skipped ▁ as ▁ ▁ we ' ll never encounter this character in the string because it has been added just now ; Find the next character that hasn 't occurred yet ; Driver code
def nextZero ( i , occurrences ) : NEW_LINE INDENT while i < 26 : NEW_LINE INDENT if occurrences [ i ] == 0 : NEW_LINE INDENT return i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def getModifiedString ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if n > 26 : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT ch = str NEW_LINE ch = list ( ch ) NEW_LINE occurrences = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT occurrences [ ord ( ch [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT index = nextZero ( 0 , occurrences ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if occurrences [ ord ( ch [ i ] ) - ord ( ' a ' ) ] > 1 : NEW_LINE INDENT occurrences [ ord ( ch [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE ch [ i ] = chr ( ord ( ' a ' ) + index ) NEW_LINE occurrences [ index ] = 1 NEW_LINE index = nextZero ( index + 1 , occurrences ) NEW_LINE DEDENT DEDENT ch = ' ' . join ( ch ) NEW_LINE print ( ch ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE getModifiedString ( str ) NEW_LINE DEDENT