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
Minimum Changes To Make Alternating Binary String INPUT String s = "0010" 0 idx 0 0 idx 1 1 idx 2 0 idx 3 Two Possible Targets: Pattern 1: starts with 0 0 1 0 1 Pattern 2: starts with 1 1 0 1 0 ALGORITHM STEPS 1 Initialize counter count1 = 0 (mismatches) 2 Single Pass Compare each char with expected for pattern "0101" 3 Count mismatches expected = i % 2 i=0: s[0]='0' exp='0' OK i=1: s[1]='0' exp='1' DIFF +1 i=2: s[2]='1' exp='0' OK i=3: s[3]='0' exp='1' OK count1 = 1 count2 = n - count1 = 3 4 Return minimum min(count1, count2) FINAL RESULT Original: "0010" 0 0 1 0 After 1 change: 0 1 0 1 Alternating: "0101" Output 1 min(1, 3) = 1 change Key Insight: There are only 2 valid alternating patterns: "0101..." and "1010...". Count mismatches for one pattern, and the mismatches for the other pattern = n - count1. Return the minimum of both counts. Time: O(n) | Space: O(1) -- Single pass solution! TutorialsPoint - Minimum Changes To Make Alternating Binary String | Optimized Single Pass Approach
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