Buddy Strings in Python

Buddy strings are two strings where you can swap exactly two characters in one string to make it equal to the other string. Given two strings A and B, we need to determine if they are buddy strings.

For example, if A = "ba" and B = "ab", we can swap positions 0 and 1 in string A to get "ab", which equals B. So the output will be True.

Algorithm

To solve this problem, we need to check several conditions:

  • If lengths of A and B are different, return False
  • If A and B don't have the same character frequency, return False
  • If A equals B but all characters are distinct, return False (no duplicate to swap)
  • Count the number of different positions between A and B
  • If more than 2 positions differ, return False
  • Otherwise, return True

Implementation

class Solution:
    def buddyStrings(self, A, B):
        if len(A) != len(B):
            return False
        elif sorted(A) != sorted(B):
            return False
        elif A == B and len(set(A)) == len(A):
            return False
        else:
            count = 0
            for i in range(len(A)):
                if A[i] != B[i]:
                    count += 1
                    if count == 3:
                        return False
            return True

# Test the solution
solution = Solution()
print(solution.buddyStrings("ba", "ab"))
print(solution.buddyStrings("ab", "ba"))
print(solution.buddyStrings("aa", "aa"))
print(solution.buddyStrings("aab", "aab"))
True
True
True
True

How It Works

Let's trace through the algorithm with different examples:

Example 1: A = "ba", B = "ab"

The strings have the same length and same characters. They differ at 2 positions (0 and 1), so we can swap to make them equal.

Example 2: A = "aa", B = "aa"

The strings are identical and have duplicate characters. We can swap the two 'a' characters with each other, so the result is still valid.

Example 3: A = "ab", B = "ca"

solution = Solution()
print(solution.buddyStrings("ab", "ca"))
False

This returns False because the character frequencies don't match (A has 'a','b' but B has 'c','a').

Key Points

  • Buddy strings must have exactly the same character frequencies
  • If strings are identical, they need at least one duplicate character to be buddy strings
  • Maximum of 2 positions can differ between the strings
  • Time complexity: O(n) where n is the length of the strings
  • Space complexity: O(1) if we ignore the sorting step

Conclusion

The buddy strings algorithm efficiently checks if two strings can become equal with exactly one swap. The key insight is validating character frequencies and counting differing positions to ensure only one swap is needed.

Updated on: 2026-03-25T08:52:22+05:30

729 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements