Given a binary string, find the minimum number of character changes needed to make it alternating.
Problem
You are given a binary string s consisting only of '0' and '1'.
In one move, you may change any character in the string to the other binary digit.
A string is alternating if no two adjacent characters are the same. For example, 0101 and 1010 are alternating, while 0110 is not.
Return the minimum number of moves required to make s alternating.
Key Idea
For an alternating string, there are only two possible target patterns:
- starts with
0:010101... - starts with
1:101010...
Compute how many positions differ from each pattern and return the smaller count.
Input Format
A single binary string s.
1 <= s.length
Output Format
Return an integer representing the minimum number of changes required so that the string becomes alternating.
Constraints
scontains only characters'0'and'1'.- The answer is guaranteed to fit in a 32-bit signed integer.
Example 1
Input
s = "0100"
Output
1
Explanation
Change the last character from '0' to '1' to get "0101".
Example 2
Input
s = "10"
Output
0
Explanation
The string is already alternating.
Show 1 more example
Example 3
Input
s = "1111"
Output
2
Explanation
Both target patterns require two changes: "1010" or "0101".
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.