Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of minimum swaps required to make it palindrome in Python
A palindrome is a string that reads the same forwards and backwards. To transform a string into a palindrome using minimum adjacent swaps, we need to check if it's possible and then calculate the swaps required.
For a string to form a palindrome, at most one character can have an odd frequency (which would be the middle character in odd-length palindromes).
Algorithm
The solution involves two steps:
Check if palindrome formation is possible by counting character frequencies
Use two pointers to match characters from both ends, swapping adjacent elements when needed
Example
Let's implement the solution to find minimum swaps required ?
class Solution:
def solve(self, s):
def util(s):
seen = {}
for char in s:
seen[char] = seen.get(char, 0) + 1
odd_count = 0
for count in seen.values():
if count % 2 == 1:
odd_count += 1
if odd_count >= 2:
return False
return True
swaps = 0
if util(s):
left = 0
right = len(s) - 1
s = list(s)
while left < right:
if s[left] != s[right]:
k = right
while k > left and s[k] != s[left]:
k -= 1
if k == left:
swaps += 1
s[left], s[left + 1] = s[left + 1], s[left]
else:
while k < right:
s[k], s[k + 1] = s[k + 1], s[k]
k += 1
swaps += 1
left += 1
right -= 1
else:
left += 1
right -= 1
return swaps
return -1
# Test the solution
ob = Solution()
s = "xxyy"
print(f"Input: {s}")
print(f"Minimum swaps: {ob.solve(s)}")
Input: xxyy Minimum swaps: 2
How It Works
For the string "xxyy":
Check feasibility: All characters have even frequency (x:2, y:2), so palindrome is possible
Use two pointers: left=0, right=3
s[0]='x' != s[3]='y', find matching 'x' from right side
Swap adjacent elements to bring matching character to the correct position
Continue until left >= right
Testing with Different Cases
ob = Solution()
test_cases = ["xxyy", "abc", "aab", "racecar"]
for test in test_cases:
result = ob.solve(test)
print(f"'{test}' -> {result if result != -1 else 'Not possible'}")
'xxyy' -> 2 'abc' -> Not possible 'aab' -> 1 'racecar' -> 0
Conclusion
The algorithm first validates palindrome possibility by checking character frequencies, then uses adjacent swaps to match characters from both ends. Time complexity is O(n²) where n is the string length.
