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
Buddy Strings: Can One Swap Make Strings Equal?Case 1: Different Positionsabcs[0]s[1]s[2]bacgoal[0]goal[1]goal[2]Swap s[0]↔s[1] ✓Case 2: Identical with Duplicatesaas[0]s[1]aagoal[0]goal[1]Can swap duplicates ✓Both cases allow exactly one swap to make strings equal
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
Asked in
Google 12 Facebook 8
59.1K Views
Medium Frequency
~15 min Avg. Time
1.8K 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