Problem statement

https://leetcode.com/problems/one-edit-distance/

Solution

Check different options: if they have the same length, than we need to check if they differ in one place. If they length differ by $1$, than we compare symbols one by one and if they are different, than we move one pointer ahead and continue. If we have one more difference, return false. Also if lengths differ by more than $1$, also return false.

Complexity

It is $\mathcal{O}(m+n)$, where $m$ is the length of the first string and $n$ is the length of the second string.

Code

class Solution:
    def isOneEditDistance(self, s, t):
        m, n = len(s), len(t)
        if m == n: return sum(i != j for i, j in zip(s, t)) == 1
        if abs(m - n) > 1: return False
        
        if m > n: return self.isOneEditDistance(t, s)
        
        i1, i2 = 0, 0
        while i1 < m and i2 < n:
            if s[i1] == t[i2]:
                i1, i2 = i1 + 1, i2 + 1
            else:
                i2 += 1
                
        return i1 == m