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.
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.
This is a String Simulation problem.
s. If so, you can swap the duplicates and the string remains the same (return true).s makes it equal to goal.s = "ab", goal = "ba": Diff at indices 0 and 1. Swap 'a' and 'b' in s to get "ba". True.s = "ab", goal = "ab": Equal. No duplicates. Cannot swap to keep "ab". False.s = "aa", goal = "aa": Equal. Duplicate 'a' exists. Swap them to get "aa". True.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.
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.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Largest Substring Between Two Equal Characters | Easy | Solve | |
| Rings and Rods | Easy | Solve | |
| Single-Row Keyboard | Easy | Solve | |
| Count the Number of Special Characters I | Easy | Solve | |
| Permutation Difference between Two Strings | Easy | Solve |