5 Best Ways to Check if Characters of One String Can Be Swapped to Form Another in Python

Rate this post

πŸ’‘ Problem Formulation: Given two strings, the task is to determine whether we can swap characters in the first string to match the second. For instance, by swapping ‘a’ and ‘b’ in “abc”, we can form “bac”. Conversely, “abx” cannot be rearranged into “abc” because ‘x’ replaces ‘c’ and there’s no ‘x’ in the target string.

Method 1: Sorting and Comparing

This method involves sorting the characters of both strings and then comparing them. Since the characters must be swapped to form the other, both strings, when sorted, should be identical. It’s efficient and can be easily implemented in Python using the sorted() method.

Here’s an example:

def can_swap_to_form(s1, s2):
    return sorted(s1) == sorted(s2)

print(can_swap_to_form('abc', 'cba')) # True
print(can_swap_to_form('abx', 'abc')) # False

Output:

True
False

This code snippet defines a function can_swap_to_form() that takes two strings as input. It returns True if the sorted characters of both strings are equal, indicating that you can swap characters in one string to form the other, and False otherwise.

Method 2: Using Counter from Collections

The Counter class from the collections module can be used to count the frequency of each character in the strings. If both strings have identical character frequencies, one can be transformed into the other through swapping. The Counter objects can be compared directly for this purpose.

Here’s an example:

from collections import Counter

def can_be_swapped(s1, s2):
    return Counter(s1) == Counter(s2)

print(can_be_swapped('listen', 'silent')) # True
print(can_be_swapped('hello', 'bello')) # False

Output:

True
False

The function can_be_swapped() uses the Counter class to compare the character counts of each string. If the counts are the same, the function returns True, otherwise it returns False.

Method 3: Using Set and Length Check

This method involves converting the strings into sets and comparing their lengths with the original strings. If their set lengths and actual lengths are the same, and the sets are equal, the characters can be swapped to form the second string. This method assumes no duplicate characters are present in the input strings.

Here’s an example:

def swap_possible(s1, s2):
    return set(s1) == set(s2) and len(s1) == len(s2)

print(swap_possible('abcd', 'dbca')) # True
print(swap_possible('aabb', 'bbaa')) # False

Output:

True
False

The swap_possible() function compares the sets and lengths of two strings. It works correctly only if there are no repeating characters since sets ignore duplicate elements.

Method 4: Frequency Dictionary

Creating a frequency dictionary for each string and comparing them is another approach to solving the problem. This method is akin to Method 2 but done manually without the collections module, which can be useful in environments where external modules are restricted.

Here’s an example:

def same_char_swap(s1, s2):
    def create_freq_dict(s):
        freq = {}
        for char in s:
            freq[char] = freq.get(char, 0) + 1
        return freq

    return create_freq_dict(s1) == create_freq_dict(s2)

print(same_char_swap('apple', 'ppale')) # True
print(same_char_swap('apple', 'applf')) # False

Output:

True
False

This snippet introduces a helper function create_freq_dict() that builds a frequency dictionary for a given string. The same_char_swap() function then compares the dictionaries of two strings to see if they match.

Bonus One-Liner Method 5: Using Python Sets

Taking advantage of Python’s powerful set operations, we can condense the check into a one-liner. This method quickly evaluates whether the set of characters in both strings are equal. This works for strings without duplicate characters.

Here’s an example:

swap_possible = lambda s1, s2: len(s1) == len(s2) and set(s1) == set(s2)

print(swap_possible('react', 'trace')) # True
print(swap_possible('react', 'race'))  # False

Output:

True
False

This one-liner defines a lambda function that checks whether the two strings have equal lengths and character sets, which implies the possibility of swapping.

Summary/Discussion

  • Method 1: Sorting and Comparing. Simple and Pythonic. It involves an extra cost of sorting, which is O(n log n), and it does not account for duplicates effectively.
  • Method 2: Using Counter from Collections. Clean and efficient, especially for strings with duplicate characters. It can be less efficient for very long strings due to the overhead of counting.
  • Method 3: Using Set and Length Check. Fast for strings without duplicates, but fails when there are repeating characters in the strings.
  • Method 4: Frequency Dictionary. Offers fine-grained control and does not need external libraries. It is more verbose and can be slower than using Counter.
  • Bonus Method 5: Using Python Sets. Extremely concise, but works only when strings have unique characters. It’s less versatile compared to other methods.