#859
Buddy Strings
EasyHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach involves counting the differences between the two strings and checking specific conditions to determine if a valid swap can be made. This is more efficient than checking all pairs.
⚙️
Algorithm
6 steps- 1Step 1: If the lengths of `s` and `goal` are not equal, return false.
- 2Step 2: Initialize a list to store the indices where `s` and `goal` differ.
- 3Step 3: Iterate through the strings and collect indices of differing characters.
- 4Step 4: If there are exactly two differing indices, check if swapping those characters results in equality.
- 5Step 5: If there are no differing indices and there are duplicate characters in `s`, return true (indicating a swap of identical characters).
- 6Step 6: Otherwise, return false.
solution.py9 lines
1def buddyStrings(s, goal):
2 if len(s) != len(goal): return False
3 diff = []
4 for i in range(len(s)):
5 if s[i] != goal[i]:
6 diff.append(i)
7 if len(diff) == 2:
8 return s[diff[0]] == goal[diff[1]] and s[diff[1]] == goal[diff[0]]
9 return len(diff) == 0 and len(set(s)) < len(s)ℹ
Complexity note: The time complexity is O(n) because we only need to iterate through the strings once to find differences. The space complexity is O(n) due to the storage of differing indices.
- 1Swapping requires exactly two differing characters to match the goal.
- 2Identical characters can be swapped if they exist in the string.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.