#1247

Minimum Swaps to Make Strings Equal

specialist · 645 · lc medium +30 · verified · 65.3% accepted · 1,468 likes · top 70%

Description

You are given two equal-length strings s1 and s2, each containing only 'x' and 'y'. Your goal is to make both strings identical. In one swap, you may pick any index i in s1 and any index j in s2 and exchange s1[i] with s2[j].

Return the minimum number of such cross-string swaps needed, or -1 if it is impossible.

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

Code

1
2
3