Minimum Flips to Make Binary String Coherent Problem
#3922
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3922.
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.
Example 1:
Input: s = "1010"
Output: 1
Explanation:
Flip s[0] to get "0010", which contains no "011" or "110" subsequences.
Example 2:
Input: s = "0110"
Output: 1
Explanation:
Flip s[1] to get "0010", removing all forbidden subsequences "011" and "110".
Example 3:
Input: s = "1000"
Output: 0
Explanation:
The string already has no "011" or "110" subsequences, so no flips are needed.
Constraints:
1 <= s.length <= 10^5s[i]is either'0'or'1'.
Solution
Approach: Enumerate the Coherent Shapes
First work out which strings contain neither "011" nor "110" as a subsequence. Let the ones be at positions p1 < p2 < ... < pm.
- With at most one
'1'there is nothing to match, so the string is coherent. - With two or more ones, a
'0'after the second one gives"110", and a'0'before the second-to-last one gives"011". Form >= 3every position is one of these, so no zero is allowed: the string is all ones. Form = 2the only allowed zeros sit between the two ones, so the string looks like1 0...0 1.
So a coherent string is one of: at most one '1', all '1', or '1' followed by zeros followed by '1'. The cost of each shape is easy to count:
- At most one
'1': flip all ones but one,max(0, ones - 1). - All ones: flip every zero,
n - ones. 1 0...0 1(needsn >= 2): the first and last characters must be'1', and every'1'in between must be flipped.
The answer is the minimum of the three.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minFlips(self, s: str) -> int:
n = len(s)
ones = s.count("1")
# Coherent strings: at most one '1', all '1's, or '1' + zeros + '1'.
ans = min(max(0, ones - 1), n - ones)
if n >= 2:
middle_ones = ones - (s[0] == "1") - (s[-1] == "1")
ans = min(ans, (s[0] == "0") + (s[-1] == "0") + middle_ones)
return ans