Store the last occurrence of each character in the map .
Dictionary < char , int > mp = new Dictionary < char , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . ContainsKey ( s [ i ] ) ) mp [ s [ i ] ] = i ; else mp . Add ( s [ i ] , i ) ; } int f = 0 ;