Buddy Strings (LeetCode 859): Solution and Explanation
Decide whether exactly one swap of two letters in s makes it equal to goal. The swap is mandatory, even when the strings already match.
Intuition
A swap touches exactly two positions and leaves every other position alone. So after the swap, s can only equal goal if s and goal already agree everywhere except at those two positions.
That splits the problem into two cases. If s and goal differ somewhere, the differences must be at exactly two indices i and j, and swapping must move the right letters into place: s[i] has to equal goal[j] and s[j] has to equal goal[i].
If s already equals goal, the swap still has to happen. Swapping two different letters would break the match, so the only safe swap exchanges two copies of the same letter. The answer is true exactly when some letter appears twice.
Both checks are a single scan, and the seen set never holds more than 26 letters.
Approach: Mismatch count plus cross check
- If the lengths differ, return false.
- If
s == goal, scan s with a set of seen letters and return true at the first repeat; return false if there is none. - Otherwise scan both strings and record indices where they differ. A third mismatch means false right away.
- If there are not exactly two mismatches, return false.
- With mismatches i and j, return
s[i] == goal[j] and s[j] == goal[i].
Step-by-step example
s = "ab", goal = "ba"
- Both strings have length 2, and they are not equal, so look for mismatches.
- Index 0: s has a, goal has b. Record 0.
- Index 1: s has b, goal has a. Record 1.
- Exactly two mismatches, at 0 and 1.
- s[0] = a equals goal[1] = a, and s[1] = b equals goal[0] = b, so the swap works. Return true.
Code: Python, Java, C++
1class Solution:
2 def buddyStrings(self, s: str, goal: str) -> bool:
3 if len(s) != len(goal):
4 return False
5 if s == goal:
6 seen = set()
7 for ch in s:
8 if ch in seen:
9 return True
10 seen.add(ch)
11 return False
12 diffs = []
13 for i in range(len(s)):
14 if s[i] != goal[i]:
15 if len(diffs) == 2:
16 return False
17 diffs.append(i)
18 if len(diffs) != 2:
19 return False
20 i, j = diffs
21 return s[i] == goal[j] and s[j] == goal[i]1class Solution {
2 public boolean buddyStrings(String s, String goal) {
3 if (s.length() != goal.length()) {
4 return false;
5 }
6 if (s.equals(goal)) {
7 boolean[] seen = new boolean[26];
8 for (char ch : s.toCharArray()) {
9 if (seen[ch - 'a']) {
10 return true;
11 }
12 seen[ch - 'a'] = true;
13 }
14 return false;
15 }
16 int[] diffs = new int[2];
17 int count = 0;
18 for (int i = 0; i < s.length(); i++) {
19 if (s.charAt(i) != goal.charAt(i)) {
20 if (count == 2) {
21 return false;
22 }
23 diffs[count++] = i;
24 }
25 }
26 if (count != 2) {
27 return false;
28 }
29 int i = diffs[0], j = diffs[1];
30 return s.charAt(i) == goal.charAt(j) && s.charAt(j) == goal.charAt(i);
31 }
32}1class Solution {
2public:
3 bool buddyStrings(string s, string goal) {
4 if (s.size() != goal.size()) {
5 return false;
6 }
7 if (s == goal) {
8 vector<bool> seen(26, false);
9 for (char ch : s) {
10 if (seen[ch - 'a']) {
11 return true;
12 }
13 seen[ch - 'a'] = true;
14 }
15 return false;
16 }
17 int diffs[2];
18 int count = 0;
19 for (int i = 0; i < (int)s.size(); i++) {
20 if (s[i] != goal[i]) {
21 if (count == 2) {
22 return false;
23 }
24 diffs[count++] = i;
25 }
26 }
27 if (count != 2) {
28 return false;
29 }
30 int i = diffs[0], j = diffs[1];
31 return s[i] == goal[j] && s[j] == goal[i];
32 }
33};Time and space complexity
O(n)
Each branch reads the strings once, and the mismatch scan can stop early at a third mismatch.
O(1)
The mismatch list holds at most two indices and the seen set at most 26 letters.
Other approaches
Try every swap (time O(n^3), space O(n))
For each pair i < j, swap s[i] and s[j] and compare with goal. It follows the statement literally but costs quadratic swaps, each with a linear comparison.
Letter counts for the equal case (time O(n), space O(1))
Count the 26 letters and check whether any count is at least 2. It gives the same answer as the seen set, but always reads the whole string.
Common mistakes
- Returning true when s == goal without a repeated letter. In Example 2, "ab" must be swapped, which produces "ba".
- Accepting two mismatches without checking the cross. "ab" vs "cd" differs in two places, but no swap fixes it.
- Forgetting the length check, which makes the index scan read past the shorter string.
Frequently asked questions
Why is a repeated letter enough when the strings are equal?
Swapping two equal letters changes nothing, so s stays equal to goal after the required swap.
Can one mismatch ever be fixed?
No. A swap changes two positions, and if only one position is wrong, the other swapped position was correct and becomes wrong unless the letters are equal, in which case the wrong one stays wrong.
Why stop at the third mismatch?
One swap fixes at most two positions, so a third mismatch already decides the answer and the rest of the scan is wasted work.