Convert given string so that it holds only distinct characters | Java 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 ; Return the modified string ; Driver code
class GFG { static int nextZero ( int i , int occurrences [ ] ) { while ( i < occurrences . length ) { if ( occurrences [ i ] == 0 ) return i ; i ++ ; } return - 1 ; } static String getModifiedString ( String str ) { int n = str . length ( ) ; if ( n > 26 ) return " - 1" ; char ch [ ] = str . toCharArray ( ) ; int i , occurrences [ ] = new int [ 26 ] ; 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 ) ; } } return String . valueOf ( ch ) ; } public static void main ( String arr [ ] ) { String str = " geeksforgeeks " ; System . out . print ( getModifiedString ( str ) ) ; } }