Problem
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
s
to gett
. - Delete exactly one character from
s
to gett
. - Replace exactly one character of
s
with a different character to gett
.
OR
Another way to put the problem Two words are friends if they have a Levenshtein distance of 1. That is, you can add, remove, or substitute exactly one letter in word X to create word Y. A word’s social network consists of all of its friends, plus all of their friends, and all of their friends’ friends, and so on. Write a program to tell us how big the social network for the word “causes” is, using this word list. Have fun!
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Iteration
To determine if two strings are one edit distance apart, consider the three allowed operations:
- Insertion
- Deletion
- Replacement
Steps
- Length Check:
- If the absolute difference in their lengths is greater than 1, they can’t be one edit distance apart.
- Iteration and Comparison:
- Iterate through both strings simultaneously.
- Compare characters at each position.
- If characters differ, check for the possible operations:
- Insertion/Deletion: If the lengths are different, shift the pointer of the longer string.
- Replacement: If the lengths are the same, shift both pointers.
- If more than one difference is found, return
false
.
- Edge Cases:
- Consider edge cases where the strings differ exactly by one character in length (requires appending the last character).
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of the shorter stringmin(len(s), len(t))
. The entire string is traversed once. - 🧺 Space complexity:
O(1)
as we use a constant amount of extra space.