Minimum Number of Flips to Make the Binary String Alternating - Problem

You are given a binary string s and need to transform it into an alternating pattern using the minimum number of flips.

Two operations are allowed:

  • Type-1 (Rotate): Remove the first character and append it to the end
  • Type-2 (Flip): Change any '0' to '1' or '1' to '0'

An alternating string has no two adjacent characters that are the same. Examples: "010", "1010", "10101"

Goal: Find the minimum number of Type-2 operations (flips) needed after performing any number of Type-1 operations (rotations) to make the string alternating.

Example: For s = "111000", we can rotate to get "110001", then flip 2 characters to get "101010" (alternating).

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "111000"
โ€บ Output: 2
๐Ÿ’ก Note: We can rotate to position 2 to get "100011", then flip 2 characters to make "101010" (alternating pattern starting with '1'). This gives us the minimum number of flips needed.
example_2.py โ€” Already Alternating After Rotation
$ Input: s = "010"
โ€บ Output: 0
๐Ÿ’ก Note: The string is already alternating, so no flips are needed. We can achieve this with 0 rotations and 0 flips.
example_3.py โ€” Single Character
$ Input: s = "1"
โ€บ Output: 0
๐Ÿ’ก Note: A single character is always alternating by definition, so no flips are needed regardless of rotations.

Visualization

Tap to expand
The Necklace Repair ShopOriginal Necklace: "111000"111000Optimal Rotation: "100011"100011Target: Alternating PatternOnly 2 beads need repainting!Minimum Flips: 2Red beads show flips needed๐Ÿ’ก Insight: Try all starting positions to find the one requiring minimum changes
Understanding the Visualization
1
Original Necklace
We start with a necklace that may not follow the alternating pattern
2
Try Different Starting Points
We can rotate the necklace to start from any bead position
3
Count Repainting Needed
For each starting position, count how many beads need color changes
4
Find Optimal Solution
Choose the starting position that requires minimum repainting
Key Takeaway
๐ŸŽฏ Key Insight: By using a sliding window on the doubled string, we can efficiently examine all possible rotations and find the optimal starting position that minimizes the number of flips needed to create an alternating pattern.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the doubled string with sliding window

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track counts and minimum

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s[i] is either '0' or '1'
  • Time limit: 1 second per test case
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
26.0K Views
Medium Frequency
~25 min Avg. Time
890 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