Minimum Swaps to Make Strings Equal Problem
Description
LeetCode Problem 1247.
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation: Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you cannot swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Constraints:
1 <= s1.length, s2.length <= 1000s1.length == s2.lengths1, s2only contain'x'or'y'.
Solution
Approach: Count the Two Kinds of Mismatch
Positions where s1[i] == s2[i] are already fine. The other positions come in two kinds:
xy:s1has'x'ands2has'y';yx:s1has'y'ands2has'x'.
Now look at what one swap can fix:
- Two
xypositionsiandj: swaps1[i]withs2[j]. Both strings get'y'atiand'x'atj, so one swap fixes two. The same holds for twoyxpositions. - One
xyand oneyx: first swap at the same index to turn one of them into the other kind, then the pair is of the same kind. That takes two swaps.
So we pair up mismatches of the same kind as much as possible: xy / 2 + yx / 2 swaps. If both counts are odd, one xy and one yx are left, which cost 2 more. If exactly one count is odd (xy + yx is odd), the total number of 'x' in both strings is odd, so they can never be split evenly and the answer is -1.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
xy = yx = 0 # mismatched positions: s1 has 'x' and s2 'y', or the other way round
for a, b in zip(s1, s2):
if a == "x" and b == "y":
xy += 1
elif a == "y" and b == "x":
yx += 1
if (xy + yx) % 2 == 1: # the total number of x's is odd: they cannot be split evenly
return -1
# Two "xy" (or two "yx") are fixed by one swap; one "xy" with one "yx" needs two.
return xy // 2 + yx // 2 + 2 * (xy % 2)