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" and goal = "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
๐Ÿ•ต๏ธ The String Detective InvestigationWitness Statement A:TOMWitness Statement B:TMO12Differences detected!๐Ÿ” Detective's Analysis:โ€ข Found exactly 2 discrepanciesโ€ข Position 1: 'O' โ†” 'M' (can be swapped)โ€ข Conclusion: Buddy strings confirmed! โœ“After the swap:TMOPerfect match!
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!
Asked in
Google 28 Amazon 22 Meta 18 Microsoft 15
24.3K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen