Minimum distance between duplicates in a String | Java Program to find the minimum distance between two repeating characters in a String using two pointers technique ; 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 ; Driver code ; Given Input ; Function Call
import java . util . * ; class GFG { static int shortestDistance ( String s , int n ) { int [ ] visited = new int [ 128 ] ; Arrays . fill ( visited , - 1 ) ; int ans = Integer . MAX_VALUE ; for ( int right = 0 ; right < n ; right ++ ) { char c = s . charAt ( right ) ; int left = visited ; if ( left != - 1 ) ans = Math . min ( ans , right - left - 1 ) ; visited = right ; } return ans == Integer . MAX_VALUE ? - 1 : ans ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int n = 13 ; System . out . print ( shortestDistance ( s , n ) ) ; } }