Program to find minimum swaps required to make given anagram in python



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 −

  • Define a function util() . This will take S, T, i
  • if i >= size of S , then
    • return 0
  • if S[i] is same as T[i], then
    • return util(S, T, i + 1)
  • x := T[i]
  • ret := 99999
  • for j in range i + 1 to size of T, do
    • if x is same as S[j], then
      • swap S[i] and S[j]
      • ret := minimum of ret and (1 + util(S, T, i + 1))
      • swap S[i] and S[j]
  • return ret
  • From the main method do the following:
  • return util(S, T, 0)

Let us see the following implementation to get better understanding −

Example 

Live Demo

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))

Input

"kolkata", "katloka"

Output

3
Updated on: 2020-12-02T05:33:15+05:30

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements