Minimum Flips to Make the Binary String Alternate

Doubled string sliding window — for each length-n window, count mismatches against "0101..." and "1010..." patterns.

Medium
Time O(n) Space O(1)
LeetCode
5 min read
string sliding-window

Problem#

You may rotate the string and flip any bit. Return the minimum flips to make the string alternate (0101... or 1010...).

Examples#

  • "111000"2.
  • "010"0; "1110"1.

Constraints#

  • 1 <= s.length <= 10^5.

Approach#

Concatenate s with itself to simulate all rotations. Sliding window of length n: count mismatches against the two alternating patterns. Track the minimum mismatch count.

Solution#

Minimum Flips to Make the Binary String Alternate
class Solution {
public:
int minFlips(string s) {
int n = s.size();
string t = s + s;
int diff0 = 0, diff1 = 0, ans = INT_MAX;
for (int i = 0; i < (int)t.size(); ++i) {
char want0 = (i & 1) ? '1' : '0';
char want1 = (i & 1) ? '0' : '1';
if (t[i] != want0) ++diff0;
if (t[i] != want1) ++diff1;
if (i >= n) {
char p0 = ((i - n) & 1) ? '1' : '0';
char p1 = ((i - n) & 1) ? '0' : '1';
if (t[i - n] != p0) --diff0;
if (t[i - n] != p1) --diff1;
}
if (i >= n - 1) ans = min(ans, min(diff0, diff1));
}
return ans;
}
};

Editorial#

Rotation is naturally a sliding window over s + s. Computing mismatches against both patterns simultaneously in one sweep is O(n) total; the trick is being careful about the index parity comparisons when both adding and removing window elements.

Complexity#

  • Time: O(n).
  • Space: O(n) for t, O(1) extra logic.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.