Convert given string so that it holds only distinct characters | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nextZero ( int i , int occurrences [ ] ) { while ( i < 26 ) { if ( occurrences [ i ] == 0 ) return i ; i ++ ; } return -1 ; } string getModifiedString ( string str ) { int n = str . length ( ) ; if ( n > 26 ) return " - 1" ; string ch = str ; int i , occurrences [ 26 ] = { 0 } ; for ( i = 0 ; i < n ; i ++ ) occurrences [ ch [ i ] - ' a ' ] ++ ; int index = nextZero ( 0 , occurrences ) ; for ( i = 0 ; i < n ; i ++ ) { if ( occurrences [ ch [ i ] - ' a ' ] > 1 ) { occurrences [ ch [ i ] - ' a ' ] -- ; ch [ i ] = ( char ) ( ' a ' + index ) ; occurrences [ index ] = 1 ; index = nextZero ( index + 1 , occurrences ) ; } } cout << ch << endl ; } int main ( ) { string str = " geeksforgeeks " ; getModifiedString ( str ) ; }