Smallest character in a string having minimum sum of distances between consecutive repetitions | Python3 program for the above approach ; Function to find the character repeats with minimum distance ; Stores the first and last index ; Intialize with - 1 ; Get the values of last and first occurence ; Update the first index ; Update the last index ; Intialize the min ; Get the minimum ; Values must not be same ; Update the minimum distance ; return ans ; Driver Code ; Function call
import sys NEW_LINE def minDistChar ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE first = [ ] NEW_LINE last = [ ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT first . append ( - 1 ) NEW_LINE last . append ( - 1 ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( first [ ord ( s [ i ] ) - ord ( ' a ' ) ] == - 1 ) : NEW_LINE INDENT first [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i NEW_LINE DEDENT last [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i NEW_LINE DEDENT min = sys . maxsize NEW_LINE ans = '1' NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( last [ i ] == first [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( min > last [ i ] - first [ i ] ) : NEW_LINE INDENT min = last [ i ] - first [ i ] NEW_LINE ans = i + ord ( ' a ' ) NEW_LINE DEDENT DEDENT return chr ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE print ( minDistChar ( str ) ) NEW_LINE DEDENT