Store the last occurrence of each character in the map .
Map < Character , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mp . put ( s . charAt ( i ) , i ) ; } int cnt = 0 , f = 0 ;