- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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]

- if x is same as S[j], then
- return ret
- From the main method do the following:
- return util(S, T, 0)

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

"kolkata", "katloka"

3

- Related Questions & Answers
- Program to count number of minimum swaps required to make it palindrome in Python
- Minimum swaps required to make a binary string alternating in C++
- Program to find minimum remove required to make valid parentheses in Python
- Program to find number of swaps required to sort the sequence in python
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Minimum Swaps to Make Strings Equal in C++
- Minimum Swaps To Make Sequences Increasing in C++
- Program to find minimum number of operations required to make one number to another in Python
- Program to find minimum swaps to arrange a binary grid using Python
- Program to find minimum adjacent swaps for K consecutive ones in Python
- Program to find minimum swaps needed to group all 1s together in Python
- Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character in C++
- Using Counter() in Python 3.x. to find minimum character removal to make two strings anagram
- Program to find minimum number of operations required to make one string substring of other in Python
- Program to find minimum number of deletions required from two ends to make list balanced in Python

Advertisements