Traverse from right and update res as soon as we see a visited character .
int res = -1 ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( visited [ str [ i ] ] == false ) visited [ str [ i ] ] = true ; else res = i ; } return res ; }