#3666

Minimum Operations to Equalize Binary String

Hard
MathStringBreadth-First SearchUnion-FindOrdered SetBFSState Space Exploration
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of brute-forcing through combinations, we can model the number of zeros and track their changes through valid operations using BFS.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of zeros in the string.
  2. 2Step 2: Use BFS to explore how many operations are needed to reach zero zeros, considering the parity of zeros after each operation.
  3. 3Step 3: Return the minimum operations or -1 if not possible.
solution.py17 lines
1from collections import deque
2
3def min_operations(s, k):
4    z = s.count('0')
5    n = len(s)
6    queue = deque([(z, 0)])
7    visited = set([z])
8    while queue:
9        curr_z, ops = queue.popleft()
10        if curr_z == 0:
11            return ops
12        for i in range(max(0, k - (n - curr_z)), min(k, curr_z) + 1):
13            next_z = curr_z + k - 2 * i
14            if next_z not in visited:
15                visited.add(next_z)
16                queue.append((next_z, ops + 1))
17    return -1

Complexity note: The BFS explores states efficiently, leading to linear time complexity in terms of the number of zeros.

  • 1Understanding the parity of zeros after flips is crucial.
  • 2BFS allows us to explore states efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.