Minimum distance between duplicates in a String | C # 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
using System ; using System . Collections . Generic ; public class GFG { static int shortestDistance ( String S , int N ) { Dictionary < char , int > dic = new Dictionary < char , int > ( ) ; List < int > dis = new List < int > ( ) ; int var ; for ( int i = 0 ; i < N ; i ++ ) { if ( dic . ContainsKey ( S [ i ] ) ) { var = i - dic [ S [ i ] ] ; dic [ S [ i ] ] = i ; dis . Add ( var ) ; } else { dic . Add ( S [ i ] , i ) ; } } dis . Sort ( ) ; if ( dis . Count == 0 ) return - 1 ; else return dis [ 0 ] - 1 ; } public static void Main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = 13 ; Console . WriteLine ( shortestDistance ( S , N ) ) ; } }