Minimum Suffix Flips Problem
Description
LeetCode Problem 1529.
You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target.
In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'.
Return the minimum number of operations needed to make s equal to target.
Example 1:
Input: target = "10111"
Output: 3
Explanation: Initially, s = "00000".
Choose index i = 2: "00000" -> "00111"
Choose index i = 0: "00111" -> "11000"
Choose index i = 1: "11000" -> "10111"
We need at least 3 flip operations to form target.
Example 2:
Input: target = "101"
Output: 3
Explanation: Initially, s = "000".
Choose index i = 0: "000" -> "111"
Choose index i = 1: "111" -> "100"
Choose index i = 2: "100" -> "101"
We need at least 3 flip operations to form target.
Example 3:
Input: target = "00000"
Output: 0
Explanation: We do not need any operations since the initial s already equals target.
Constraints:
n == target.length1 <= n <= 10^5target[i]is either'0'or'1'.
Solution
Approach: Count the Changes Between Neighbors
Look at the bits from left to right. The first bit target[0] can only be changed by the operation at index 0, and after deciding about index 0, the second bit can only be fixed by the operation at index 1, and so on. So there is no choice to make: go left to right and flip at index i exactly when bit i is wrong at that moment.
We never need to keep the whole string. Every flip so far started at or before i, so all of them covered bit i and everything after it. After flips operations, every remaining bit equals flips % 2. If that differs from target[i], flip at i and add one.
Put differently, the answer is the number of places where target changes from one bit to the next, plus one if target[0] is '1'. For "10111" the changes are 1 -> 0 and 0 -> 1, plus the leading 1: 3 operations. A target of all zeros needs none.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minFlips(self, target: str) -> int:
flips = 0
for c in target:
# After `flips` suffix flips, every bit from here on is flips % 2.
if flips % 2 != int(c):
flips += 1
return flips