Magicsheet logo

Buddy Strings

Easy
66.5%
Updated 6/1/2025

Asked by 3 Companies

Buddy Strings

What is this problem about?

Given two strings s and goal, can you swap exactly two characters in s so that it becomes equal to goal? This "Buddy Strings" coding problem tests your ability to handle string comparisons and edge cases.

Why is this asked in interviews?

Companies like Google and Zoho use this to test basic logic and attention to detail. It sounds simple, but you have to handle cases where the strings are already equal (where a swap is only possible if there are duplicate characters) and cases where they differ in exactly two positions.

Algorithmic pattern used

This is a String Simulation problem.

  1. If lengths are different, return false.
  2. If the strings are equal, check if there are any duplicate characters in s. If so, you can swap the duplicates and the string remains the same (return true).
  3. If the strings are different, find all indices where they differ.
    • If there are exactly two differences, check if swapping those two characters in s makes it equal to goal.
    • Otherwise, return false.

Example explanation

  1. s = "ab", goal = "ba": Diff at indices 0 and 1. Swap 'a' and 'b' in s to get "ba". True.
  2. s = "ab", goal = "ab": Equal. No duplicates. Cannot swap to keep "ab". False.
  3. s = "aa", goal = "aa": Equal. Duplicate 'a' exists. Swap them to get "aa". True.

Common mistakes candidates make

Failing to handle the "already equal" case is the most common mistake. Many candidates assume that if the strings are equal, the answer is always true or always false, without checking for duplicates. Another mistake is not checking if the swapped characters actually match the goal.

Interview preparation tip

Always look for the "swap identical characters" edge case in string problems. It's a classic trick to see if a candidate considers all possibilities, even those that don't change the visible output.

Similar Questions