Buddy Strings using Python

Buddy Strings is a popular problem in coding interviews. In this problem, you need to check if it is possible to get two strings, different from exactly a swap of two letters. So, if you want to learn how to solve this problem, this article is for you. In this article, I’ll take you through how to solve the Buddy Strings problem using Python.

Buddy Strings Problem

In the Buddy Strings problem, you need to check if it is possible to get two strings, different from exactly a swap of two letters. If such a swap exists, the program should return True; otherwise, it should return False. The program should also return False if the two strings have different lengths.

Here’s an example of the input and output values of this problem:

  • Input: s = “ab”, goal = “ba” | Output: True

The output of the above example is true because we can swap the a and b in string s to get the desired goal.

Check Buddy Strings using Python

I hope you have understood what the Buddy Strings problem means. Now here’s how to solve this problem using Python:

def buddyStrings(s, goal):
    if len(s) != len(goal):
        return False
    if s == goal:
        return len(set(s)) < len(s)
    diffs = [(a, b)for a, b in zip(s, goal) if a != b]
    return len(diffs) == 2 and diffs[0] == diffs[1][::-1]

s = "ab"
goal = "ba"

print(buddyStrings(s, goal))
Output: True

Below is how the above code works:

  1. The function first takes two strings s and goal as input.
  2. Then, it checks if s and goal have the same length. If they do not have the same length, the function returns False.
  3. If s and goal are the same string, the function checks if there are repeated characters in s. If there are repeated characters, we can swap them so that s and goal are the same.
  4. If s and goal are not the same string, the function finds the indices where s and goal differ. It then checks that there are only two differences between s and goal and that these differences can be swapped so that s and goal are the same.
  5. Finally, the function returns True if the conditions are met, and False otherwise.

So this is how you can solve the Buddy Strings problem using Python. You can find many more practice questions for coding interviews solved and explained using Python here.

Summary

In the Buddy Strings problem, you need to check if it is possible to get two strings, different from exactly a swap of two letters. If such a swap exists, the program should return True; otherwise, it should return False. I hope you liked this article on how to solve the Buddy Strings problem using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1435

Leave a Reply