Program to determine if two strings are close in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings, s and t, we have to check whether s and t are close or not. We can say two strings are close if we can attain one from the other using the following operations −

  • Exchange any two existing characters. (like abcde to aecdb)

  • Change every occurrence of one existing character into another existing character, and do the same with the other characters also. (like aacabb -> bbcbaa (here all a's are converted to b's, and vice versa))

We can use the operations on either string as many times as we want.

So, if the input is like s = "zxyyyx", t = "xyyzzz", then the output will be true, because we can get t from s in 3 operations. ("zxyyyx" -> "zxxyyy"), ("zxxyyy" -> "yxxzzz"), and ("yxxzzz" -> "xyyzzz").

To solve this, we will follow these steps −

  • if s and t have any uncommon character, then

    • return False

  • a := list of all frequency values of characters in s

  • b := list of all frequency values of characters in t

  • sort the list a

  • sort the list b

  • if a is not same as b, then

    • return False

  • return True


Let us see the following implementation to get better understanding −

from collections import Counter
def solve(s, t):
   if set(s) != set(t):
      return False
   a = list(Counter(s).values())
   b = list(Counter(t).values())
   if a != b:
      return False
   return True

s = "zxyyyx"
t = "xyyzzz"
print(solve(s, t))


"zxyyyx", "xyyzzz"


Published on 06-Oct-2021 07:40:53