#K35732. Minimum Swaps to Transform a String
Minimum Swaps to Transform a String
Minimum Swaps to Transform a String
You are given two strings S1 and S2 of equal length. Your task is to compute the minimum number of swaps required to transform S1 into S2 by swapping any two characters. If it is impossible to do so, output -1.
More formally, you need to find the smallest number of swaps such that after performing these swaps on S1
, the resulting string becomes S2
. Note that if the two strings have different multisets of characters (i.e. \(\text{sorted}(S_1) \neq \text{sorted}(S_2)\)), the transformation is impossible, and you should return -1.
Input Format: The first line contains an integer T, the number of test cases. For each test case, the first line contains an integer N (the length of the strings), followed by two lines containing the strings S1
and S2
respectively.
Output Format: For each test case, output the minimum number of swaps required. If the transformation is not possible, output -1.
Consider the following examples:
- Example 1: For S1 = "abcd" and S2 = "badc", the minimum number of swaps required is 2.
- Example 2: For S1 = "abcd" and S2 = "dcba", the minimum number of swaps required is also 2.
- Example 3: For S1 = "abc" and S2 = "xyz", the transformation is impossible, so the answer is -1.
inputFormat
The first line of input contains an integer T, the number of test cases. For each test case, the following three lines are provided:
- An integer N representing the length of the strings.
- A string S1.
- A string S2.
You must read inputs from standard input (stdin).
outputFormat
For each test case, output a single line containing the minimum number of swaps required to transform S1 into S2, or -1 if it is not possible. Write your outputs to standard output (stdout).
## sample2
4
abcd
badc
4
abcd
dcba
2
2
</p>