Program to check whether one string swap can make strings equal or not using Python


Suppose we have two strings s and t of same length. Consider an operation where we choose two indices in a string (not necessarily different) and swap the characters at the selected indices. We have to check whether it is possible to make both strings same by performing at most one string swap on exactly one of the strings or not.

So, if the input is like s = "hello" t = "hlelo", then the output will be True because we need to swap 'e' and 'l' at either s or t to make them equal.

To solve this, we will follow these steps −

  • max_diffs:= 2

  • diffs:= 0

  • st := a new set

  • st2 := a new set

  • for i in range 0 to size of s, do

    • if s[i] is not same as t[i], then

      • diffs := diffs + 1

    • if s[i] not present in st, then

      • insert s[i] into st

    • if t[i] not present in st2, then

      • insert t[i] into st2

    • if diffs > max_diffs, then

      • return False

  • return true if (diffs is same as 0 or diffs is same as 2) and size of st is same as size of st2 and st is same as st2, otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(s, t):
   max_diffs=2
   diffs=0
   st = set()
   st2 = set()
   for i in range(len(s)):
      if s[i] != t[i]:
         diffs+=1
      if s[i] not in st:
         st.add(s[i])
      if t[i] not in st2:
         st2.add(t[i])
      if diffs > max_diffs:
         return False
   return (diffs == 0 or diffs == 2) and len(st) == len(st2) and st == st2
s = "hello"
t = "hlelo"
print(solve(s, t))

Input

"hello", "hlelo"

Output

True

Updated on: 29-May-2021

327 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements