Count minimum substring removals required to reduce string to a single distinct character | Python3 program for the above approach ; Function to find minimum removals required to convert given string to single distinct characters only ; Unordered map to store positions of characters X , Y and Z ; Update indices of X , Y , Z ; ; Stores the count of minimum removals ; Traverse the Map ; Count the number of removals required for current character ; Update the answer ; Print the answer ; Driver Code ; Given string ; Size of string ; Function call
import sys ; NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def minimumOperations ( s , n ) : NEW_LINE INDENT mp = { } ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] in mp : NEW_LINE INDENT mp [ s [ i ] ] . append ( i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT mp [ s [ i ] ] = [ i ] ; NEW_LINE DEDENT DEDENT ans = INT_MAX ; NEW_LINE for x in mp : NEW_LINE INDENT curr = 0 ; NEW_LINE prev = 0 ; NEW_LINE first = True ; NEW_LINE for index in mp [ x ] : NEW_LINE INDENT if ( first ) : NEW_LINE INDENT if ( index > 0 ) : NEW_LINE INDENT curr += 1 ; NEW_LINE DEDENT prev = index ; NEW_LINE first = False ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( index != prev + 1 ) : NEW_LINE INDENT curr += 1 ; NEW_LINE DEDENT prev = index ; NEW_LINE DEDENT DEDENT if ( prev != n - 1 ) : NEW_LINE INDENT curr += 1 ; NEW_LINE DEDENT ans = min ( ans , curr ) ; NEW_LINE DEDENT print ( ans ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " YYXYZYXYZXY " ; NEW_LINE N = len ( s ) ; NEW_LINE minimumOperations ( s , N ) ; NEW_LINE DEDENT