Ctrl K

Cross Swaps of x and y

Medium
You get two strings top and bottom of equal length, made of the letters x and y. Your goal is to make them identical. In one move you pick any character of top and any character of bottom and exchange them: top[i] ↔ bottom[j], where i and j may differ. Swapping two characters within the same string is not allowed. Return the smallest number of moves after which the strings match, or -1 if that is impossible.
Example 1
top="xy", bottom="yx" → 2

Two mismatches of different kinds. First swap top[0] with bottom[0] to get "yy" and "xx", then swap top[0] with bottom[1]: both strings read "xy". Two swaps in total.

Example 2
top="xxyx", bottom="yyyx" → 1

Positions 0 and 1 differ, both with x on top and y below. A single swap of top[0] and bottom[1] turns both strings into "yxyx".

Example 3
top="xy", bottom="xx" → -1

There are three x letters in total, an odd number, so they cannot be split evenly between the strings.

Constraints
  • 1 ≤ len(top) ≤ 1000
  • len(top) = len(bottom)
  • The strings contain only x and y
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRound Prices to a Total MediumLucky Ticket With Blanks MediumSandwiched Chip Duel MediumErase Digits Until It Divides by 25 MediumThe Biggest Odd Chunk Easy
loading Python…
Input
top="xy", bottom="yx"
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 106 tests on the server, hidden ones included.