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

You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:

Type-1: Remove the character at the start of the string s and append it to the end of the string.

Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.

Return the minimum number of type-2 operations you need to perform such that s becomes alternating.

The string is called alternating if no two adjacent characters are equal.

For example, the strings "010" and "1010" are alternating, while the string "0100" is not.

Input & Output

Example 1 — Basic Case
$ Input: s = "11000"
Output: 1
💡 Note: We can rotate to get "00011" or "01100", then flip 1 character to make it alternating like "01010" or "10101".
Example 2 — Already Alternating After Rotation
$ Input: s = "10"
Output: 0
💡 Note: The string is already alternating, so no type-2 operations (flips) are needed.
Example 3 — Single Character
$ Input: s = "1"
Output: 0
💡 Note: A single character is always alternating by definition.

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either '0' or '1'

Visualization

Tap to expand
Transform "11000" to Alternating Pattern11000Input: "11000"Rotate + Count Flips01100Best Rotation: "01100" → Flip 1 bit0Result: "01010" (alternating)Answer: 1
Understanding the Visualization
1
Input
Binary string "11000" that needs to become alternating
2
Rotate + Flip
Try different rotations and count minimum flips needed
3
Output
Minimum number of type-2 operations (flips) required
Key Takeaway
🎯 Key Insight: Try all possible rotations and find the one requiring minimum flips to become alternating
Asked in
Meta 15 Google 12 Microsoft 8
28.4K Views
Medium Frequency
~25 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