Minimum Changes To Make Alternating Binary String - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "0010"
›
Output:
1
💡 Note:
To make "0010" alternating, we can either match pattern "0101" (needs 2 changes at positions 1 and 3) or pattern "1010" (needs 1 change at position 0). The minimum is 1.
Example 2 — Already Alternating
$
Input:
s = "010"
›
Output:
0
💡 Note:
String is already alternating (0-1-0), so no changes needed.
Example 3 — All Same Characters
$
Input:
s = "1111"
›
Output:
2
💡 Note:
To make alternating: Pattern "0101" needs 4 changes, Pattern "1010" needs 2 changes. Minimum is 2.
Constraints
- 1 ≤ s.length ≤ 104
- s[i] is either '0' or '1'
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code