Program to find minimum changes required for alternating binary string in Python

Suppose we have a binary string s. Let us consider an operation where we can flip one bit. The string s is called alternating string if no two adjacent characters are same. We have to find the minimum number of operations needed to make s alternating.

So, if the input is like s = "11100011", then the output will be 3 because if we flip bits at position 1, 4 and 7, then, it will be "10101010", then all are alternating.

Approach

The key insight is that there are only two possible alternating patterns:

  • Pattern 1: Starting with '0' ? "0101010..."
  • Pattern 2: Starting with '1' ? "1010101..."

We count mismatches for both patterns and return the minimum changes required.

Algorithm Steps

To solve this, we will follow these steps ?

  • change := 0
  • even_1 := 0, even_0 := 0 (count of 1s and 0s at even positions)
  • odd_1 := 0, odd_0 := 0 (count of 1s and 0s at odd positions)
  • for i in range 0 to size of s - 1, do
    • if i is even, then count 1s and 0s at even positions
    • otherwise, count 1s and 0s at odd positions
  • Calculate changes for both patterns and return minimum

Example

Let us see the following implementation to get better understanding ?

def solve(s):
    change = 0
    even_1 = 0
    even_0 = 0
    odd_1 = 0
    odd_0 = 0
    
    for i in range(len(s)):
        if i % 2 == 0:  # Even position
            if s[i] == '1':
                even_1 += 1
            else:
                even_0 += 1
        else:  # Odd position
            if s[i] == '1':
                odd_1 += 1
            else:
                odd_0 += 1
    
    # Pattern 1: "010101..." - changes needed: even_1 + odd_0
    # Pattern 2: "101010..." - changes needed: even_0 + odd_1
    change = min(even_1 + odd_0, even_0 + odd_1)
    return change

s = "11100011"
print(f"Input: {s}")
print(f"Minimum changes required: {solve(s)}")
Input: 11100011
Minimum changes required: 3

How It Works

For string "11100011":

  • Even positions (0,2,4,6): '1','1','0','1' ? even_1=3, even_0=1
  • Odd positions (1,3,5,7): '1','0','0','1' ? odd_1=2, odd_0=2
  • Pattern "0101...": Changes = even_1 + odd_0 = 3 + 2 = 5
  • Pattern "1010...": Changes = even_0 + odd_1 = 1 + 2 = 3
  • Minimum: 3 changes

Optimized Solution

Here's a more concise version that directly counts pattern mismatches ?

def min_changes_alternating(s):
    # Count mismatches for pattern starting with '0'
    pattern1_changes = sum(1 for i, char in enumerate(s) if char != str(i % 2))
    
    # Count mismatches for pattern starting with '1'  
    pattern2_changes = len(s) - pattern1_changes
    
    return min(pattern1_changes, pattern2_changes)

# Test with example
test_string = "11100011"
result = min_changes_alternating(test_string)
print(f"String: {test_string}")
print(f"Minimum changes: {result}")
String: 11100011
Minimum changes: 3

Conclusion

The algorithm counts positions where the string doesn't match either alternating pattern ("0101..." or "1010...") and returns the minimum changes needed. The time complexity is O(n) and space complexity is O(1).

Updated on: 2026-03-25T20:35:09+05:30

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements