1529. Minimum Suffix Flips
October 30, 2025 · View on GitHub
Description
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 <= 105target[i]is either'0'or'1'.
Solutions
Solution 1: Greedy
We traverse the string from left to right, using a variable to record the number of flips. When we reach index , if the parity of the current flip count is different from , we need to perform a flip operation at index and increment by $1$.
The time complexity is , where is the length of the string. The space complexity is .
Python3
class Solution:
def minFlips(self, target: str) -> int:
ans = 0
for v in target:
if (ans & 1) ^ int(v):
ans += 1
return ans
Java
class Solution {
public int minFlips(String target) {
int ans = 0;
for (int i = 0; i < target.length(); ++i) {
int v = target.charAt(i) - '0';
if (((ans & 1) ^ v) != 0) {
++ans;
}
}
return ans;
}
}
C++
class Solution {
public:
int minFlips(string target) {
int ans = 0;
for (char c : target) {
int v = c - '0';
if ((ans & 1) ^ v) {
++ans;
}
}
return ans;
}
};
Go
func minFlips(target string) int {
ans := 0
for _, c := range target {
v := int(c - '0')
if ((ans & 1) ^ v) != 0 {
ans++
}
}
return ans
}
TypeScript
function minFlips(target: string): number {
let ans = 0;
for (const c of target) {
if (ans % 2 !== +c) {
++ans;
}
}
return ans;
}
Rust
impl Solution {
pub fn min_flips(target: String) -> i32 {
let mut ans = 0;
for c in target.chars() {
let bit = (c as u8 - b'0') as i32;
if ans % 2 != bit {
ans += 1;
}
}
ans
}
}