Store the last occurrence of each character in the map .
var mp = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( mp . has ( s [ i ] ) ) { mp . set ( s [ i ] , mp . get ( s [ i ] ) + 1 ) ; } else mp . set ( s [ i ] , 1 ) ; } var cnt = 0 , f = 0 ;