Buddy Strings in Python

Suppose we have two strings A and B of lowercase letters; we have to check whether we can swap two letters in A so that the result equals to B or not.

So, if the input is like A = "ba", B = "ab", then the output will be True.

To solve this, we will follow these steps −

  • if size of A is not same as size of B, then
    • return False
  • otherwise when A and B has any element that are not common, then
    • return False
  • otherwise when A is same as B and all characters are distinct in A, then
    • return False
  • otherwise,
    • count:= 0
  • for i in range 0 to size of A, do
    • if A[i] is not same as B[i], then
      • count := count + 1
      • if count is same as 3, then
        • return False
  • return True

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def buddyStrings(self, A, B):
      if len(A)!=len(B):
         return False
      elif sorted(A)!=sorted(B):
         return False
      elif A==B and len(set(A))==len(A):
         return False
         for i in range(len(A)):
            if A[i]!=B[i]:
               if count==3:
                  return False
         return True
ob = Solution()





Updated on: 04-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started