Program to determine if two strings are close in Python

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

Algorithm

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 both lists a and b

  • If a is not same as b, then return False

  • Return True

Example

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())
    a.sort()
    b.sort()
    if a != b:
        return False
    return True

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

How It Works

The algorithm works by checking two conditions ?

  • Same character set: Both strings must contain the same unique characters

  • Same frequency pattern: The frequency counts must have the same distribution when sorted

For example, in "zxyyyx" we have frequencies [1, 1, 4] for [z, x, y], and in "xyyzzz" we have [1, 2, 3] for [x, y, z]. After sorting: [1, 1, 4] vs [1, 2, 3]. Since they don't match, let's check a working example ?

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())
    a.sort()
    b.sort()
    return a == b

# Working example
s1 = "abc"
t1 = "bca"
print(f"'{s1}' and '{t1}' are close: {solve(s1, t1)}")

# Another example
s2 = "aabbcc"
t2 = "ccaabb"
print(f"'{s2}' and '{t2}' are close: {solve(s2, t2)}")

# Non-working example
s3 = "abc"
t3 = "def"
print(f"'{s3}' and '{t3}' are close: {solve(s3, t3)}")
'abc' and 'bca' are close: True
'aabbcc' and 'ccaabb' are close: True
'abc' and 'def' are close: False

Conclusion

Two strings are close if they have the same character set and the same frequency distribution pattern. Use Counter to get frequencies and compare both the unique characters and sorted frequency values.

Updated on: 2026-03-26T13:59:50+05:30

534 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements