Program to check two strings are 0 or 1 edit distance away or not in Python


Suppose we have two strings S and T we have to check whether they are one or zero edit distance away or not. An edit operation can be defined as deleting a character, adding a character, or replacing a character with another character.

So, if the input is like S = "hello", T = "hallo", then the output will be True, as these two strings have edit distance of 1.

To solve this, we will follow these steps −

  • m := size of S, n := size of T
  • i := 0, j := 0
  • count := 0
  • if |m - n| > 1, then
    • return False
  • while i < m and j < n, do
    • if S[i] is not same as T[j], then
      • if count is same as 1, then
        • return False
      • if m < n, then
        • j := j + 1
      • otherwise when m > n, then
        • i := i + 1
      • otherwise,
        • i := i + 1, j := j + 1
      • count := count + 1
    • otherwise,
      • i := i + 1, j := j + 1
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, S, T):
      m, n = len(S), len(T)
      i, j = 0, 0
      count = 0
      if abs(m - n) > 1:
         return False
      while i < m and j < n:
         if S[i] != T[j]:
            if count == 1:
               return False
            if m < n:
               j += 1
            elif m > n:
               i += 1
            else:
               i += 1
               j += 1
            count += 1
         else:
            i += 1
            j += 1
      return True
ob = Solution()
S = "hello"
T = "hallo"
print(ob.solve(S, T))

Input

"hello", "hallo"

Output

True

Updated on: 19-Oct-2020

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements