Skip to main content
Back to problems
#1758
Easy Algorithms

Minimum changes to make alternating binary string

String
63.8% acceptance
Feb 25, 2026
1500
43
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the minimum number of operations needed to make s alternating.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(s: String) -> i32 {
    // Count mismatches with "010101..." pattern
    let cost1 = s.bytes().enumerate()
      .filter(|&(i, c)| c - b'0' != (i % 2) as u8)
      .count() as i32;
    // Mismatches with "101010..." = n - cost1
    cost1.min(s.len() as i32 - cost1)
  }
}