[LeetCode] Minimum Flips to Make Binary String Coherent

3922. Minimum Flips to Make Binary String Coherent

You are given a binary string s.

A string is considered coherent if it does not contain "011" or "110" as subsequences.

In one operation, you can flip any character in s ('0' to '1' or '1' to '0').

Return an integer denoting the minimum number of operations required to make s coherent.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int minFlips(string s) {
int res = INT_MAX, one = count(begin(s), end(s), '1'), n = s.length();
if(n <= 2) return 0;
res = min(one, n - one);
if(one) res = min(res, one - 1);
if(s[0] == '1') one--;
if(s[n-1] == '1') one--;
res = min(res, one);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-flips-to-make-binary-string-coherent/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.