Minimum replacements in a string to make adjacent characters unequal | Function which counts the minimum number of required operations ; n stores the length of the string s ; ans will store the required ans ; i is the current index in the string ; Move j until characters s [ i ] & s [ j ] are equal or the end of the string is reached ; diff stores the length of the substring such that all the characters are equal in it ; We need atleast diff / 2 operations for this substring ; Driver code
def count_minimum ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT j = i NEW_LINE while j < n and ( s [ j ] == s [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT diff = j - i NEW_LINE ans += diff // 2 NEW_LINE i = j NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " caaab " NEW_LINE count_minimum ( str ) NEW_LINE DEDENT