Minimum Operations to Transform Binary String Problem
Description
LeetCode Problem 3980.
You are given two binary strings s1 and s2 of the same length n.
You can perform the following operations on s1 any number of times, in any order:
- Choose an index
isuch thats1[i] == '0', and change it to'1'. - Choose an index
isuch that0 <= i < n - 1, and boths1[i]ands1[i + 1]are'1'. Change both characters to'0'.
Return the minimum number of operations required to make s1 equal to s2. If it is impossible, return -1.
Example 1:
Input: s1 = "11", s2 = "00"
Output: 1
Explanation:
Change indices 0 and 1 from '1' to '0' in one operation, so "11" becomes "00". Thus, the answer is 1.
Example 2:
Input: s1 = "01", s2 = "10"
Output: 3
Explanation:
- Change index 0 from '0' to '1', so "01" becomes "11".
- Change indices 0 and 1 from '1' to '0', so "11" becomes "00".
- Change index 0 from '0' to '1', so "00" becomes "10".
- Thus, the answer is 3.
Example 3:
Input: s1 = "1", s2 = "0"
Output: -1
Explanation:
The first operation cannot change '1' to '0', and the second operation requires two adjacent characters. Therefore, it is impossible.
Constraints:
1 <= n == s1.length == s2.length <= 10^5s1ands2consist only of'0'and'1'.
Solution
Approach: Counting the pair operations
Let P be the number of "11 -> 00" operations and F the number of "0 -> 1" operations. Every pair operation removes two ones and every flip adds one, so ones(s1) + F - 2P = ones(s2). The total cost is F + P = ones(s2) - ones(s1) + 3P, which means we only need to minimize P.
A position with s1[i] = 1 and s2[i] = 0 must be zeroed, and the only way to do that is a pair operation that covers it. Zeros can always be flipped to ones first, so any set of adjacent pairs covering all such positions can be carried out. The problem becomes covering these positions with as few adjacent pairs as possible: scan from left to right and, whenever a position is not covered yet, place a pair on it and the next index (or the previous one when it is the last index). If n = 1 and the single position must go from 1 to 0, the answer is -1.
Complexity: time O(n), space O(1).
class Solution:
def minOperations(self, s1: str, s2: str) -> int:
n = len(s1)
pairs = 0
covered = -1
for i in range(n):
if s1[i] == '1' and s2[i] == '0' and i > covered:
if n == 1:
return -1
pairs += 1
covered = i + 1
return s2.count('1') - s1.count('1') + 3 * pairs