← Questions
One edit distance: are two strings exactly one edit apart
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Return whether two strings are exactly one edit apart, where an edit inserts one character, deletes one character or replaces one character. Equal strings are zero edits apart, so they return False. Clarify the edge cases before coding, then solve it in one pass.
Interface
Unless you agree on a different interface with the interviewer, assume:
is_one_edit_distance(s: str, t: str) -> bool
Example
is_one_edit_distance("ab", "acb") -> True # insert "c"
is_one_edit_distance("cab", "ad") -> False
is_one_edit_distance("1203", "1213") -> True # replace "0" with "1"
is_one_edit_distance("abc", "abc") -> False # zero edits
is_one_edit_distance("", "a") -> True
is_one_edit_distance("", "") -> False
Constraints
-
0 <= len(s), len(t) <= 10^5; any characters. - Target
O(n)time andO(1)extra space.
Clarifying questions
- Do equal strings count as one edit apart?
- Are empty strings allowed?
- Is the comparison case-sensitive?
- Exactly one edit, or at most one?
What a strong answer covers
- If lengths differ by more than one, return
False; makesthe shorter string. - Walk both strings to the first mismatch: with equal lengths, the rest must match after skipping one character in each (replace); with lengths differing by one, the rest of the shorter must match the longer after skipping one character there (insert).
- If no mismatch is found, the answer is
Trueonly when the lengths differ by one. - Comparing tails by index rather than slicing to keep
O(1)space. - Tests: both empty, one empty, the mismatch at the last character, equal strings.
Follow-ups
- At most
kedits apart, efficiently for smallk(banded edit distance). - Return the edit itself (which operation, where).
- Check many words against a dictionary for one-edit neighbours.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
