Minimum distance between duplicates in a String | This function is used to find minimum distance between any two repeating characters using two - pointers and hashing technique ; hash array to store character 's last index ; Traverse through the String ; If the character is present in visited array find if its forming minimum distance ; update current character 's last index ; Return minimum distance found , else - 1 ; Given Input ; Function Call
function shortestDistance ( s , n ) { var visited = Array ( 128 ) . fill ( - 1 ) ; var ans = Number . MAX_VALUE ; for ( var right = 0 ; right < n ; right ++ ) { var left = visited [ s . charCodeAt ( right ) ] ; if ( left != - 1 ) ans = Math . min ( ans , right - left - 1 ) ; visited [ s . charCodeAt ( right ) ] = right ; } return ans == Number . MAX_VALUE ? - 1 : ans ; } var s = " " ; var n = 13 ; document . write ( shortestDistance ( s , n ) ) ;