Buddy Strings — LeetCode 859 Python Solution
- Problem
- #859
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two strings s and goal, return true if you can swap two letters in s so 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].
Example
- Input
- s = "ab", goal = "ba"
- Output
- true
- Explanation
- You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Python solution
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
m, n = len(s), len(goal)
if m != n:
return False
cnt1, cnt2 = Counter(s), Counter(goal)
if cnt1 != cnt2:
return False
diff = sum(s[i] != goal[i] for i in range(n))
return diff == 2 or (diff == 0 and any(v > 1 for v in cnt1.values()))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 859. Buddy Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 859. Buddy Strings?
- LeetCode 859. Buddy Strings is rated Easy on LeetCode.
- What is the time complexity of LeetCode 859. Buddy Strings?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 859. Buddy Strings?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 859. Buddy Strings cover?
- LeetCode 859. Buddy Strings is tagged Hash Table and String on LeetCode.