Apply Operations to Make Two Strings Equal
01 · Problem
You are given two binary strings s1 and s2 of the same length n, and a positive integer x. You may apply the following operations to s1 any number of times, in any order:
- Pick any two indices
iandj(i != j, not necessarily adjacent) and flip boths1[i]ands1[j]. This costsx. - Pick an index
iwithi + 1 < nand flip boths1[i]ands1[i + 1]. This costs1.
Flipping a character turns '0' into '1' and vice versa. Return the minimum total cost to make s1 identical to s2, or -1 if it cannot be done. If the strings are already equal, return 0.
02 · Examples
s1 = "10110", s2 = "01101", x = 3
2
The strings differ at indices 0, 1, 3 and 4. Flip the adjacent pair (0, 1) for cost 1 and the adjacent pair (3, 4) for cost 1, for a total of 2.
s1 = "1001", s2 = "0000", x = 5
3
Indices 0 and 3 must change. Flipping them together costs 5, but flipping (0, 1), then (1, 2), then (2, 3) costs only 3: index 1 and index 2 are each flipped twice and end unchanged.
s1 = "100", s2 = "000", x = 2
-1
Every operation flips exactly two characters, so the number of mismatched positions keeps its parity. One mismatch can never be fixed.
03 · Constraints
- 01n == s1.length == s2.length
- 021 <= n <= 500
- 031 <= x <= 500
- 04s1[i] and s2[i] are either '0' or '1'
04 · Optimal complexity
- Time
- O(n)
- Space
- O(n)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.