Lexicographically smallest string formed by removing duplicates | Function that finds lexicographically smallest string after removing the duplicates from the given string ; Stores the frequency of characters ; Mark visited characters ; Stores count of each character ; Stores the resultant string ; Decrease the count of current character ; If character is not already in answer ; Last character > S [ i ] and its count > 0 ; Mark letter unvisited ; Add s [ i ] in res and mark it visited ; Return the resultant string ; Given string S ; Function Call
function removeDuplicateLetters ( s ) { var cnt = Array ( 26 ) . fill ( 0 ) ; var vis = Array ( 26 ) . fill ( false ) ; var n = s . length ; for ( var i = 0 ; i < n ; i ++ ) cnt [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; var res = " " ; for ( var i = 0 ; i < n ; i ++ ) { cnt [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] -- ; if ( ! vis [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ) { while ( res . length > 0 && res [ res . length - 1 ] . charCodeAt ( 0 ) > s [ i ] . charCodeAt ( 0 ) && cnt [ res [ res . length - 1 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] > 0 ) { vis [ res [ res . length - 1 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] = 0 ; res = res . substring ( 0 , res . length - 1 ) ; } res += s [ i ] ; vis [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] = 1 ; } } return res ; } var S = " " ; document . write ( removeDuplicateLetters ( S ) ) ;