https://leetcode.com/problems/buddy-strings

Let us carefully cover all possible cases in this problem:

  1. If lengths of strings are different, we immedietly return False.
  2. If counters of strings are different, we also return False.
  3. Let us also evaluate for each place if symbols in A and B are equal. We can afford to have only 2 symbols which are not equal or 0: in first case we change two different symbols and in second two equal. So, if number of not equal symbols is not 0 or 2, we return False.
  4. 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, like abtlpe, so we return False in this case.
  5. 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, like ddddddd, so we return False in this case.
  6. 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