Minimum distance between duplicates in a String | This function is used to find the required the minimum distances of repeating characters ; Define dictionary and list ; 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 characters ; Return minimum distance ; Given Input ; Function Call
def shortestDistance ( S , N ) : NEW_LINE INDENT dic = { } NEW_LINE dis = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if S [ i ] in dic : NEW_LINE INDENT var = i - dic [ S [ i ] ] NEW_LINE dic [ S [ i ] ] = i NEW_LINE dis . append ( var ) NEW_LINE DEDENT else : NEW_LINE INDENT dic [ S [ i ] ] = i NEW_LINE DEDENT DEDENT if ( len ( dis ) == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return min ( dis ) - 1 NEW_LINE DEDENT DEDENT S = " geeksforgeeks " NEW_LINE N = 13 NEW_LINE print ( shortestDistance ( S , N ) ) NEW_LINE