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 - Optimal Solution INPUT String s a idx 0 b idx 1 String goal b idx 0 a idx 1 Input Values: s = "ab" goal = "ba" ALGORITHM STEPS 1 Check Lengths len(s) == len(goal)? 2 == 2 : OK 2 Find Differences Compare char by char diff = [0, 1] 3 Check Diff Count Exactly 2 differences? len(diff) = 2 : OK 4 Verify Swap s[0]=a == goal[1]=a? s[1]=b == goal[0]=b? Both OK! Swap Check: a <--> b Match! FINAL RESULT Before Swap (s) a b SWAP After Swap b a == goal "ba" Output: true Key Insight: For exactly one swap to make s equal to goal, there must be exactly 2 positions where characters differ. The characters at these positions must be swappable: s[i]==goal[j] AND s[j]==goal[i]. Special case: if s == goal, we need duplicate characters to swap (e.g., "aa"). TutorialsPoint - Buddy Strings | Optimal Solution O(n)
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