Problem statement

https://binarysearch.com/problems/One-Edit-Distance/

Solution

Alsmost equal to Leetcode 0161 One Edit Distance.

Complexity

It is 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 solve(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.solve(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