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 ; Return the modified string ; Driver code
function nextZero ( i , occurrences ) { while ( i < occurrences . length ) { if ( occurrences [ i ] == 0 ) return i ; i ++ ; } return - 1 ; } function getModifiedString ( str ) { let n = str . length ; if ( n > 26 ) return " " ; let ch = str . split ( ' ' ) ; let occurrences = new Array ( 26 ) ; occurrences . fill ( 0 ) ; let i ; for ( i = 0 ; i < n ; i ++ ) occurrences [ ch [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] ++ ; let index = nextZero ( 0 , occurrences ) ; for ( i = 0 ; i < n ; i ++ ) { if ( occurrences [ ch [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] > 1 ) { occurrences [ ch [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] -- ; ch [ i ] = String . fromCharCode ( ' ' . charCodeAt ( ) + index ) ; occurrences [ index ] = 1 ; index = nextZero ( index + 1 , occurrences ) ; } } let s = ch . join ( " " ) ; return s ; } let str = " " ; document . write ( getModifiedString ( str ) ) ;