Program to check two strings can be equal by swapping characters or not in Python


Suppose we have two lowercase strings s and t, they are of the same length. We can select one character from s and another from t and swap them. We can do this operation any number of times we want. Finally, we have to check whether it's possible to make the two strings same or not.

So, if the input is like s = "abcd" t = "cdab", then the output will be True

To solve this, we will follow these steps −

  • fre := a list containing frequencies of each elements present in concatenated string of s and t
  • for each cnt in list of all values of fre, do
    • if cnt mod 2 is 1, then
      • return False
  • return True

Example

Let us see the following implementation to get better understanding −

from collections import Counter
def solve(s, t):
   fre = Counter(s+t)

   for cnt in fre.values():
      if cnt % 2:
         return False

   return True

s = "abcd"
t = "cdab"
print(solve(s, t))

Input

"abcd", "cdab"

Output

True

Updated on: 14-Oct-2021

582 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements