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
Minimum Flips for Alternating Binary String INPUT Binary String s 1 1 0 0 0 0 1 2 3 4 Operations Allowed: Type-1: Rotate (move first to end) Type-2: Flip any bit (0-->1, 1-->0) Target Patterns: Pattern A: 01010 Pattern B: 10101 s = "11000" ALGORITHM STEPS 1 Double the String ss = s + s = "1100011000" 2 Precompute Mismatches Count diff vs patterns A,B Sliding Window (size n=5) ss: 1 1 0 0 0 1 1 0 0 0 window slides 3 Slide Window O(n) Update counts incrementally Mismatch Counts per Rotation: Rot 0: vs A=3, vs B=2 Rot 1: vs A=2, vs B=3 Rot 2: vs A=1, vs B=4 [OK] 4 Find Minimum min(all rotations) = 1 FINAL RESULT Optimal: Rotate 2 times first Original: 11000 After 2 rotations: 00011 Compare to Pattern A (01010): 0 0 0 1 1 0 1 0 1 0 OK OK OK FLIP OK After 1 flip: 00010 0 1 0 1 0 Alternating String! Output: 1 Key Insight: By doubling the string (s+s), all possible rotations become contiguous substrings of length n. Using a sliding window, we can compute minimum flips for each rotation in O(1) time per rotation. Total complexity: O(n) instead of O(n^2). Only two target patterns exist: "0101..." and "1010..." TutorialsPoint - Minimum Number of Flips to Make the Binary String Alternating | Optimized with Precomputation
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