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: We can change s[1] = '0' to '1' to get "0110", but this isn't alternating. Better: change s[1] to '1' to get "0110" (not alternating) OR change s[2] to '0' to get "0000" (not alternating). Actually, to make "0010" alternating: Pattern "0101" needs 1 change at position 1, Pattern "1010" needs 3 changes. 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
Minimum Changes to Make Alternating Binary StringInput: "0010"0010Target Pattern 1: "0101"0101Changes needed: 1Target Pattern 2: "1010"Changes needed: 3Result: min(1, 3) = 1 change
Understanding the Visualization
1
Input String
Binary string that may not be alternating
2
Compare Patterns
Check against both possible alternating patterns
3
Minimum Changes
Return the smaller number of changes needed
Key Takeaway
🎯 Key Insight: Only two alternating patterns exist - compare against both and take the minimum
Asked in
Google 15 Facebook 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen