One Edit Distance Problem
Description
LeetCode Problem 161.
Given two strings s and t, return true if they are both one edit distance apart, otherwise return false.
A string s is said to be one distance apart from a string t if you can:
- Insert exactly one character into
sto gett. - Delete exactly one character from
sto gett. - Replace exactly one character of
swith a different character to gett.
Example 1:
Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.
Example 2:
Input: s = "", t = ""
Output: false
Explanation: We cannot get t from s by only one step.
Constraints:
0 <= s.length, t.length <= 10^4sandtconsist of lowercase letters, uppercase letters, and digits.
Solution
Approach: Find the First Difference
Swap the strings if needed so that s is the longer one, with lengths m >= n. If m - n > 1, one edit cannot fix the gap, so the answer is false.
Now walk both strings and find the first index i where s[i] != t[i]. That position has to be the one edit, and everything after it must line up exactly:
- If
m == n, the edit is a replace: the answer iss[i+1:] == t[i+1:]. - If
m == n + 1, the edit is a delete ofs[i]: the answer iss[i+1:] == t[i:].
If there is no difference in the first n characters, then t is a prefix of s, and the only possible edit is deleting the last character of s. So the answer is m == n + 1.
That last line also covers the tricky case: two equal strings (including two empty strings, as in Example 2) are zero edits apart, not one, so the answer is false.
Complexity: O(m) time. O(m) extra space for the suffix copies in most languages, which you could avoid by comparing character by character.
class Solution:
def isOneEditDistance(self, s: str, t: str) -> bool:
if len(s) < len(t): # make s the longer one
return self.isOneEditDistance(t, s)
m, n = len(s), len(t)
if m - n > 1:
return False
for i in range(n):
if s[i] != t[i]: # the first difference must be the only edit
if m == n:
return s[i + 1:] == t[i + 1:] # replace s[i]
return s[i + 1:] == t[i:] # delete s[i]
# No difference in the first n characters: s must have exactly one extra character at the end.
return m == n + 1