Minimum operation require to make first and last character same | Python3 program to find minimum operation require to make first and last character same ; Return the minimum operation require to make string first and last character same . ; Store indexes of first occurrences of characters . ; Initialize result ; Traverse through all characters ; Find first occurrence ; Update result for subsequent occurrences ; Driver Code
MAX = 256 NEW_LINE def minimumOperation ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE first_occ = [ - 1 ] * MAX NEW_LINE res = float ( ' inf ' ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT x = s [ i ] NEW_LINE if first_occ [ ord ( x ) ] == - 1 : NEW_LINE INDENT first_occ [ ord ( x ) ] = i NEW_LINE DEDENT else : NEW_LINE INDENT last_occ = n - i - 1 NEW_LINE res = min ( res , first_occ [ ord ( x ) ] + last_occ ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " bacdefghipalop " NEW_LINE print ( minimumOperation ( s ) ) NEW_LINE DEDENT