Print all distinct characters of a string in order ( 3 Methods ) | Javascript program to print distinct characters of a string . ; Function to print distinct characters in given string str [ ] ; count [ x ] is going to store count of character ' x ' in str . If x is not present , then it is going to store 0. ; index [ x ] is going to store index of character ' x ' in str . If x is not present or x is more than once , then it is going to store a value ( for example , length of string ) that cannot be a valid index in str [ ] ; Initialize counts of all characters and indexes of distinct characters . ; index [ i ] = n ; A value more than any index in str [ ] ; Traverse the input string ; Find current character and increment its count ; If this is first occurrence , then set value in index as index of it . ; If character repeats , then remove it from index [ ] ; Since size of index is constant , below operations take constant time . ; Driver code
let MAX_CHAR = 256 ; function printDistinct ( str ) { let n = str . length ; let count = new Array ( MAX_CHAR ) ; let index = new Array ( MAX_CHAR ) ; for ( let i = 0 ; i < MAX_CHAR ; i ++ ) { count [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { let x = str [ i ] . charCodeAt ( 0 ) ; ++ count [ x ] ; if ( count [ x ] == 1 && x != ' ' ) index [ x ] = i ; if ( count [ x ] == 2 ) index [ x ] = n ; } index . sort ( function ( a , b ) { return a - b } ) ; for ( let i = 0 ; i < MAX_CHAR && index [ i ] != n ; i ++ ) document . write ( str [ index [ i ] ] ) ; } let str = " " ; printDistinct ( str ) ;