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.

Your goal is to transform the given binary string into an alternating pattern using the minimum number of operations. An alternating pattern means characters alternate between '0' and '1' throughout the string.

Return the minimum number of operations needed to make s alternating.

Key Insight: There are only two possible alternating patterns for any string - one starting with '0' (like "010101...") and one starting with '1' (like "101010..."). The answer is the minimum changes needed for either pattern.

Input & Output

example_1.py โ€” Basic Alternating Pattern
$ Input: s = "0100"
โ€บ Output: 1
๐Ÿ’ก Note: We can change s[3] from '0' to '1' to get "0101", which is alternating. This requires only 1 operation, which is the minimum possible.
example_2.py โ€” Already Alternating
$ Input: s = "10"
โ€บ Output: 0
๐Ÿ’ก Note: The string "10" is already alternating (no two adjacent characters are the same), so no operations are needed.
example_3.py โ€” All Same Characters
$ Input: s = "1111"
โ€บ Output: 2
๐Ÿ’ก Note: We can change s to "1010" (2 changes) or "0101" (2 changes). Both require 2 operations, which is the minimum.

Constraints

  • 1 โ‰ค s.length โ‰ค 104
  • s[i] is either '0' or '1'

Visualization

Tap to expand
Creating a Perfect Checkerboard PatternCurrent tiles: "0100"0100Pattern 1: Start with White (0)0โœ“1โœ“0โœ“1โœ—Changes needed: 1 (flip last tile)Pattern 2: Start with Black (1)1โœ—0โœ—1โœ—0โœ“Changes needed: 3 (flip first 3 tiles)ResultPattern 1: 1 changePattern 2: 3 changesMinimum: 1
Understanding the Visualization
1
Identify Two Patterns
There are only 2 valid checkerboard patterns: Black-first or White-first
2
Count Tile Flips
For each pattern, count how many tiles need to be flipped
3
Choose Minimum
Pick the pattern that requires fewer flips
Key Takeaway
๐ŸŽฏ Key Insight: Since there are only 2 possible alternating patterns, we can solve this optimally in O(n) time by counting mismatches for both patterns simultaneously!
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
42.3K Views
High Frequency
~12 min Avg. Time
1.6K 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