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