Buddy Strings - Problem
You are given two strings s and goal. Your task is to determine if you can make s equal to goal by swapping exactly two characters in s.
Here's the twist: you must perform exactly one swap operation - no more, no less. A swap operation involves choosing two different indices i and j (where i โ j) and exchanging the characters at positions s[i] and s[j].
Examples:
- Swapping indices 0 and 2 in
"abcd"results in"cbad" - If
s = "ab"andgoal = "ba", swapping indices 0 and 1 makes them equal - If both strings are already identical but have duplicate characters, you can swap the duplicates
Return true if such a swap is possible, false otherwise.
Input & Output
example_1.py โ Basic Swap
$
Input:
s = "ab", goal = "ba"
โบ
Output:
true
๐ก Note:
We can swap s[0] = 'a' and s[1] = 'b' to get "ba" which equals goal.
example_2.py โ Identical Strings with Duplicates
$
Input:
s = "aa", goal = "aa"
โบ
Output:
true
๐ก Note:
The strings are already equal, but we can swap the two 'a' characters at positions 0 and 1.
example_3.py โ No Valid Swap
$
Input:
s = "ab", goal = "ab"
โบ
Output:
false
๐ก Note:
The strings are identical but have no duplicate characters, so any swap would make them different.
Constraints
- 1 โค s.length, goal.length โค 2 ร 104
- s and goal consist of lowercase English letters
- Must perform exactly one swap operation
Visualization
Tap to expand
Understanding the Visualization
1
Initial Investigation
Compare both statements word by word to find inconsistencies
2
Identify Discrepancies
Mark all positions where the statements differ
3
Analyze Pattern
Check if differences follow the 'buddy strings' pattern
4
Validate Theory
Confirm that swapping two positions resolves all differences
Key Takeaway
๐ฏ Key Insight: Just like a detective solving a case, we only need to track the differences. Buddy strings are possible when there are exactly 2 differences that can resolve each other through a single swap!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code