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

PythonServer Side ProgrammingProgramming

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
raja
Updated on 14-Oct-2021 10:35:29

Advertisements