Find the minimum number of single-character flips needed to make a binary string alternating.
You are given a binary string consisting only of '0' and '1'.
In one operation, you may flip any single character: change '0' to '1' or '1' to '0'.
Return the minimum number of flips required to make the string alternating, meaning no two adjacent characters are the same.
A valid alternating string can start with either '0' or '1'. Choose the cheaper of the two possibilities.
Input Format
- A binary string
s. scontains only characters'0'and'1'.
Output Format
- Return an integer: the minimum number of flips needed to transform
sinto an alternating string.
Constraints
1 <= |s| <= $10^{5}$s[i] ∈ {'0','1'}- Exactly one character may be flipped per operation.
Example 1
Input
s = "0100"
Output
1
Explanation
Two alternating targets are 0101 and 1010. The string 0100 differs from 0101 in one position, so the minimum number of flips is 1.
Example 2
Input
s = "10"
Output
0
Explanation
10 is already alternating, so no flips are needed.
Show 1 more example
Example 3
Input
s = "1111"
Output
2
Explanation
The closest alternating strings are 0101 and 1010. Each differs from 1111 in two positions, so the answer is 2.
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.