LeetCode 1247: Minimum Swaps to Make Strings Equal Solution

Master LeetCode problem 1247 (Minimum Swaps to Make Strings Equal), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1247. Minimum Swaps to Make Strings Equal

Problem Explanation

Explanation:

To make the two strings equal, we need to find pairs of characters that are not equal in the two strings and then swap them. We can start by counting the number of 'x' and 'y' characters in each string. If the total count of 'x's or 'y's in both strings is odd, it is impossible to make them equal. Otherwise, we can count the number of mismatched pairs and divide it by 2 to get the minimum number of swaps required.

  • Count the number of 'x' and 'y' characters in both strings.
  • If the total count of 'x's or 'y's is odd, return -1.
  • Count the number of mismatched pairs and return half of it.

Time Complexity: O(n) Space Complexity: O(1)

:

Solution Code

class Solution {
    public int minimumSwap(String s1, String s2) {
        int xCount = 0, yCount = 0, mismatch = 0;
        
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) == 'x' && s2.charAt(i) == 'y') {
                mismatch++;
                xCount++;
            } else if (s1.charAt(i) == 'y' && s2.charAt(i) == 'x') {
                mismatch++;
                yCount++;
            }
        }
        
        if ((xCount + yCount) % 2 != 0) {
            return -1;
        }
        
        return mismatch / 2 + xCount % 2 + yCount % 2;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1247 (Minimum Swaps to Make Strings Equal)?

This page provides optimized solutions for LeetCode problem 1247 (Minimum Swaps to Make Strings Equal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1247 (Minimum Swaps to Make Strings Equal)?

The time complexity for LeetCode 1247 (Minimum Swaps to Make Strings Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1247 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1247 in Java, C++, or Python.

Back to LeetCode Solutions