Suppose we have two strings S and T and they are anagrams of each other. We have to find the minimum number of swaps required in S to make it same as T.
So, if the input is like S = "kolkata" T = "katloka", then the output will be 3, as can swap in this sequence [katloka (given), kotlaka, koltaka, kolkata].
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def util(self, S, T, i) : S = list(S) T = list(T) if i >= len(S): return 0 if S[i] == T[i]: return self.util(S, T, i + 1) x = T[i] ret = 99999; for j in range(i + 1, len(T)): if x == S[j]: S[i], S[j] = S[j], S[i] ret = min(ret, 1 + self.util(S, T, i + 1)) S[i], S[j] = S[j], S[i] return ret def solve(self, S, T): return self.util(S, T, 0) ob = Solution() S = "kolkata" T = "katloka" print(ob.solve(S, T))