If `s`

and `t`

are one distance away then no matter it is insert or delete or replace the count of common characters must be `max(m, n) - 1`

, where `m`

is the length of `s`

and `n`

is the length of `t`

. It is easy to see that the reverse is also true.

Assume the length of common prefix (from left to right) is `i`

and the length of common suffix after `i`

(from right to left) is `j`

, the answer is then `max(m, n) - 1 == i + j`

Example 1 (1 replace)

```
s = "abcdefg", m = 7
t = "abcxefg", n = 7
i = 3, j = 3
max(m, n) - 1 == i + j is true
```

Example 2 (0 edit)

```
s = "abcdefg", m = 7
t = "abcdefg", n = 7
i = 7, j = 0
max(m, n) - 1 == i + j is false
```

Example 3 (1 insert)

```
s = "abcdefg", m = 7
t = "abcefg", n = 6
i = 3, j = 3
max(m, n) - 1 == i + j is true
```

Example 4 (1 delete 1 insert)

```
s = "abcdefg", m = 7
t = "abcefgh", n = 7
i = 3, j = 0
max(m, n) - 1 == i + j is false
```

The method is O(m+n) since any character is visited at most once.

**Java**

```
public boolean isOneEditDistance(String s, String t) {
int m = s.length(), n = t.length();
if (Math.abs(m - n) > 1) return false;
int k = Math.min(m, n);
int i = 0, j = 0;
while (i < k && s.charAt(i) == t.charAt(i)) ++i;
while (j < k - i && s.charAt(m - 1 - j) == t.charAt(n - 1 - j)) ++j;
return m + n - k - 1 == i + j;
}
// Runtime : 2ms
```

**Python**

```
def isOneEditDistance(self, s, t):
n, m = len(s), len(t)
if abs(n - m) > 1:
return False
k = min(n, m)
i = j = 0
while i < k and s[i] == t[i]:
i += 1
while j < k - i and s[~j] == t[~j]:
j += 1
return max(n, m) - (i + j) == 1
# 129 / 129 test cases passed.
# Status: Accepted
# Runtime: 40 ms
# 96.05%
```