An alternating binary string must follow one of two patterns: starting with '0' (like "010101...") or starting with '1' (like "101010..."). We simply count how many characters differ from each pattern and return the smaller count.
We use XOR to toggle the expected character at each position. Starting with 0, we XOR with 1 after each character to alternate between expecting 0 and 1.
cnt1 = 0 and expected character cur = 0 (pattern starting with '0').cur, increment cnt1.cur using XOR with 1.cur = 1 (pattern starting with '1') to get cnt2.min of cnt1 and cnt2.We can optimize by counting mismatches for only one pattern. Notice that if a position mismatches the "start with 1" pattern, it must match the "start with 0" pattern, and vice versa. So the count for one pattern plus the count for the other equals the string length.
We count mismatches for the "start with 1" pattern (where even indices should be '1' and odd indices should be '0'). The count for the "start with 0" pattern is simply length - count.
count = 0.i:i is even and s[i] == '0', increment count.i is odd and s[i] == '1', increment count.min of count and length - count.An alternating binary string can start with either '0' (giving "010101...") or '1' (giving "101010..."). A common mistake is only counting mismatches against one pattern and returning that count. You must compare against both patterns and return the minimum of the two counts, or use the relationship that the two counts sum to the string length.
When comparing characters to expected values (0 or 1), ensure proper conversion. In many languages, '0' and '1' are characters with ASCII values 48 and 49, not the integers 0 and 1. Use c - '0' or parseInt(c) to convert correctly. Directly comparing the character '0' to the integer 0 will give wrong results in most languages.