Minimum Operations to Equalize Binary String Problem
Description
LeetCode Problem 3666.
You are given a binary string s, and an integer k.
In one operation, you must choose exactly k different indices and flip each '0' to '1' and each '1' to '0'.
Return the minimum number of operations required to make all characters in the string equal to '1'. If it is not possible, return -1.
Example 1:
Input: s = "110", k = 1
Output: 1
Explanation:
- There is one '0' in s.
- Since k = 1, we can flip it directly in one operation.
Example 2:
Input: s = "0101", k = 3
Output: 2
Explanation:
One optimal set of operations choosing k = 3 indices in each operation is:
- Operation 1: Flip indices [0, 1, 3]. s changes from "0101" to "1000".
- Operation 2: Flip indices [1, 2, 3]. s changes from "1000" to "1111".
Thus, the minimum number of operations is 2.
Example 3:
Input: s = "101", k = 2
Output: -1
Explanation:
Since k = 2 and s has only one '0', it is impossible to flip exactly k indices to make all '1'. Hence, the answer is -1.
Constraints:
1 <= s.length <= 10^5s[i]is either'0'or'1'.1 <= k <= s.length
Solution
Approach: BFS over the Number of Zeros
Only the number of '0' characters matters. Let n be the length and cur the current number of zeros. An operation flips x zeros and k - x ones, so the new count is cur + k - 2x. The choice of x is limited by 0 <= x <= min(cur, k) (there are only cur zeros) and k - x <= n - cur (there are only n - cur ones). So the next count lies between l = cur + k - 2 * min(cur, k) and r = cur + k - 2 * max(k - n + cur, 0), in steps of 2: every reachable count has the same parity as cur + k.
Run a BFS on the counts 0..n, starting from the initial number of zeros, with target 0. To avoid scanning the same range again and again, keep for every count the next unvisited count of the same parity (a union-find with "skip to v + 2" links). From cur, jump to the first unvisited count at least l, visit it and every following one up to r, and mark each as visited. Each count is visited once. If 0 is never reached, the answer is -1.
Complexity: time O(n α(n)), space O(n).
from collections import deque
class Solution:
def minOperations(self, s: str, k: int) -> int:
n = len(s)
cnt0 = s.count('0')
# nxt[v]: smallest state >= v (same parity as v) that is not visited yet
nxt = list(range(n + 3))
def find(v: int) -> int:
root = v
while nxt[root] != root:
root = nxt[root]
while nxt[v] != root:
nxt[v], v = root, nxt[v]
return root
dist = [-1] * (n + 1)
dist[cnt0] = 0
nxt[cnt0] = cnt0 + 2
q = deque([cnt0])
while q:
cur = q.popleft()
if cur == 0:
return dist[0]
l = cur + k - 2 * min(cur, k)
r = cur + k - 2 * max(k - n + cur, 0)
j = find(l)
while j <= r:
dist[j] = dist[cur] + 1
nxt[j] = j + 2
q.append(j)
j = find(j)
return -1