[LeetCode] Minimum Number of Flips to Make the Binary String Alternating

1888. Minimum Number of Flips to Make the Binary String Alternating

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int minFlips(string& s) {
int len(s.length()), res(0), cur(0);
s += s;
for(int i = 0; i < len; i++) {
if((s[i] & 0b1111) != (i & 1)) cur += s[i] = 1;
else s[i] = 0;
}
res = min(cur, len - cur);
for(int i = len; i < len<<1 and res; i++) {
if((s[i] & 0b1111) != (i & 1)) ++cur;
cur -= s[i - len];
res = min(res, min(cur, len - cur));
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/08/PS/LeetCode/minimum-number-of-flips-to-make-the-binary-string-alternating/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.