Program to count operations to remove consecutive identical bits in Python

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" where there are no three consecutive identical bits.

Algorithm

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))
1

How It Works

The algorithm identifies consecutive groups of identical bits. For each group of length n, we need floor(n/3) operations to break all sequences of 3 or more consecutive identical bits. For example:

  • Group "111" (length 3) needs 1 operation
  • Group "1111" (length 4) needs 1 operation
  • Group "11111" (length 5) needs 1 operation
  • Group "111111" (length 6) needs 2 operations

Step-by-Step Example

For input "10011100" −

def solve_with_steps(s):
    l = 0
    count = 0
    print(f"Processing string: {s}")
    
    while l < len(s):
        r = l
        while r < len(s) and s[r] == s[l]:
            r += 1
        
        group_length = r - l
        operations = group_length // 3
        print(f"Group '{s[l] * group_length}' at positions {l}-{r-1}: length={group_length}, operations={operations}")
        
        count += operations
        l = r
    
    print(f"Total operations needed: {count}")
    return count

s = "10011100"
solve_with_steps(s)
Processing string: 10011100
Group '1' at positions 0-0: length=1, operations=0
Group '00' at positions 1-2: length=2, operations=0
Group '111' at positions 3-5: length=3, operations=1
Group '00' at positions 6-7: length=2, operations=0
Total operations needed: 1

Conclusion

This algorithm efficiently counts operations by grouping consecutive identical bits and applying floor division by 3. The time complexity is O(n) where n is the string length, making it optimal for this problem.

Updated on: 2026-03-26T16:35:02+05:30

328 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements