[
string
]
Leetcode 0859. Buddy Strings
https://leetcode.com/problems/buddy-strings
Let us carefully cover all possible cases in this problem:
- If lengths of strings are different, we immedietly return
False. - If counters of strings are different, we also return
False. - Let us also evaluate for each place if symbols in
AandBare equal. We can afford to have only2symbols which are not equal or0: in first case we change two different symbols and in second two equal. So, if number of not equal symbols is not0or2, we returnFalse. - Also, if we have number
diff_places == 0, it means that we changed two equal symbols. We can not do it if all string has different symbols, likeabtlpe, so we returnFalsein this case. - If we have
diff_places == 2, it means that we changed two different symbols. We can not do it if string is just one symbols repeated, likeddddddd, so we returnFalsein this case. - Finally, if we did not return anything yet, we return
True.
Complexity is O(n), because we use counters, which is linear and number of not equal symbols which is linear as well.
class Solution:
def buddyStrings(self, A, B):
if len(A) != len(B): return False
Count_A, Count_B = Counter(A), Counter(B)
if Count_A != Count_B: return False
diff_places = sum([i!=j for i,j in zip(A,B)])
if diff_places not in [0, 2]: return False
if diff_places == 0 and len(Count_A) == len(A): return False
if diff_places == 2 and len(Count_A) == 1: return False
return True
If you like the solution, you can upvote it on leetcode discussion section: Problem 0859