Leetcode Problem 1247. Minimum Swaps to Make Strings Equal

1247. Minimum Swaps to Make Strings Equal

Leetcode Solutions

Counting Mismatched Pairs

  1. Initialize two counters, xy and yx, to 0.
  2. Iterate over the characters of s1 and s2 simultaneously.
  3. If the characters at the current index are different, increment xy if s1 has 'x' and s2 has 'y', otherwise increment yx.
  4. After the iteration, check if the sum of xy and yx is odd. If it is, return -1.
  5. Calculate the minimum swaps as the sum of half of xy (since two 'xy' pairs can be fixed with one swap) and half of yx (since two 'yx' pairs can be fixed with one swap).
  6. If there is one 'xy' and one 'yx' left (i.e., both xy and yx are odd), add 2 to the minimum swaps (since it takes two swaps to fix one 'xy' and one 'yx').
  7. Return the calculated minimum swaps.
UML Thumbnail

Greedy Pair Swapping

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...