Buddy Strings - Problem
Given two strings s and goal, return true if you can swap exactly two letters in s so that the result is equal to goal, otherwise return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].
For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
Input & Output
Example 1 — Valid Swap
$
Input:
s = "ab", goal = "ba"
›
Output:
true
💡 Note:
We can swap s[0] and s[1] to get "ba". The character 'a' at position 0 becomes position 1, and 'b' at position 1 becomes position 0.
Example 2 — Invalid Different Characters
$
Input:
s = "ab", goal = "ab"
›
Output:
false
💡 Note:
The strings are already identical, but we need exactly one swap. Since there are no duplicate characters, no valid swap exists.
Example 3 — Valid with Duplicates
$
Input:
s = "aa", goal = "aa"
›
Output:
true
💡 Note:
The strings are identical and contain duplicate characters. We can swap the two 'a's (positions 0 and 1) to get the same string.
Constraints
- 1 ≤ s.length, goal.length ≤ 2 × 104
- s and goal consist of lowercase letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Two strings that may differ at some positions
2
Swap Validation
Check if exactly one swap can make them equal
3
Result
Return true if valid swap exists, false otherwise
Key Takeaway
🎯 Key Insight: Buddy strings work when there are exactly 2 different positions (swappable) or identical strings with duplicate characters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code