Minimum operation require to make first and last character same | Python program to find minimum operation require to make first and last character same ; Function to find minimum operation require to make first and last character same ; Base conditions ; If answer found ; If string is already visited ; Decrement ending index only ; Increment starting index only ; Increment starting index and decrement index ; Store the minimum value ; Driver code ; Function call
import sys NEW_LINE MAX = sys . maxsize NEW_LINE m = { } NEW_LINE Min = sys . maxsize NEW_LINE def minOperation ( s , i , j , count ) : NEW_LINE INDENT global Min , MAX NEW_LINE if ( ( i >= len ( s ) and j < 0 ) or ( i == j ) ) : NEW_LINE INDENT return MAX NEW_LINE DEDENT if ( s [ i ] == s [ j ] or count >= Min ) : NEW_LINE INDENT return count NEW_LINE DEDENT Str = str ( i ) + " | " + str ( j ) NEW_LINE if Str not in m : NEW_LINE INDENT if ( i >= len ( s ) ) : NEW_LINE INDENT m [ Str ] = minOperation ( s , i , j - 1 , count + 1 ) NEW_LINE DEDENT elif ( j < 0 ) : NEW_LINE INDENT m [ Str ] = minOperation ( s , i + 1 , j , count + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT m [ Str ] = min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) NEW_LINE DEDENT DEDENT if ( m [ Str ] < Min ) : NEW_LINE INDENT Min = m [ Str ] NEW_LINE DEDENT return m [ Str ] NEW_LINE DEDENT s = " bacdefghipalop " NEW_LINE ans = minOperation ( s , 0 , len ( s ) - 1 , 0 ) NEW_LINE if ( ans == MAX ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT