Minimum distance between duplicates in a String | Java implementation of above approach ; This function is used to find minimum distance between same repeating characters ; Define a hashmap and an arraylist ; Temporary variable ; Traverse through string ; If character present in dictionary ; Difference between current position and last stored value ; Updating current position ; Storing difference in list ; If character not in dictionary assign it with initial of its position ; If no element inserted in list i . e . no repeating characterss ; Return minimum distance ; Driver code ; Given input ; Function call
import java . io . * ; import java . util . * ; class GFG { static int shortestDistance ( String S , int N ) { HashMap < Character , Integer > dic = new HashMap < Character , Integer > ( ) ; ArrayList < Integer > dis = new ArrayList < > ( ) ; int var ; for ( int i = 0 ; i < N ; i ++ ) { if ( dic . get ( S . charAt ( i ) ) != null ) { var = i - dic . get ( S . charAt ( i ) ) ; dic . put ( S . charAt ( i ) , i ) ; dis . add ( var ) ; } else { dic . put ( S . charAt ( i ) , i ) ; } } if ( dis . size ( ) == 0 ) return - 1 ; else return Collections . min ( dis ) - 1 ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = 13 ; System . out . println ( shortestDistance ( S , N ) ) ; } }