Program to count operations to remove consecutive identical bits in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary string s, now let us consider an operation where we select a bit and flip its value from 0 to 1 or vice-versa. We have to find the minimum number of operations needed to get a string with no three identical consecutive bits.

So, if the input is like s = "10011100", then the output will be 1, because we can flip 1 to 0 the bit at index 4 to make the string "10010100" there are no three consecutive identical bits.

To solve this, we will follow these steps −

  • l := 0, count := 0
  • while l < size of s, do
    • r := l
    • while r < size of s and s[r] is same as s[l], do
      • r := r + 1
    • count := count + floor of ((r - l) / 3)
    • l := r
  • return count

Example

Let us see the following implementation to get better understanding −

def solve(s):
   l = 0
   count = 0
   while l < len(s):
      r = l
      while r < len(s) and s[r] == s[l]:
         r += 1
      count += (r - l) // 3
      l = r
   return count

s = "10011100"
print(solve(s))

Input

"10011100"

Output

1
raja
Updated on 14-Oct-2021 09:38:03

Advertisements