One Edit Distance - Problem
One Edit Distance
Given two strings
๐ Insert exactly one character into
โ๏ธ Delete exactly one character from
๐ Replace exactly one character in
Return
Note: If the strings are identical or require more than one edit, return
Given two strings
s and t, determine if they are exactly one edit distance apart. Two strings are considered one edit distance apart if you can perform exactly one of the following operations to transform string s into string t:๐ Insert exactly one character into
sโ๏ธ Delete exactly one character from
s๐ Replace exactly one character in
sReturn
true if the strings are exactly one edit distance apart, false otherwise.Note: If the strings are identical or require more than one edit, return
false. Input & Output
example_1.py โ Basic Replace
$
Input:
s = "ab", t = "acb"
โบ
Output:
true
๐ก Note:
We can insert 'c' into s to get t: "ab" โ "acb" (insert 'c' at position 1)
example_2.py โ Basic Delete
$
Input:
s = "cab", t = "ab"
โบ
Output:
true
๐ก Note:
We can remove 'c' from s to get t: "cab" โ "ab" (delete 'c' at position 0)
example_3.py โ Identical Strings
$
Input:
s = "1203", t = "1203"
โบ
Output:
false
๐ก Note:
The strings are identical, so no edit is needed. We need exactly one edit distance, not zero.
Visualization
Tap to expand
Understanding the Visualization
1
Read Side by Side
Compare characters at the same position in both strings
2
Find the Difference
Stop when you encounter the first mismatch
3
Identify Edit Type
Based on string lengths, determine if it's insert/delete/replace
4
Verify Fix
Check if the rest matches after applying the single edit
Key Takeaway
๐ฏ Key Insight: By using two pointers to find the first mismatch and then determining the edit type based on string lengths, we can solve this problem in O(n) time with O(1) space, avoiding the need to generate all possible edits.
Time & Space Complexity
Time Complexity
O(nยฒ)
For each of the O(n) positions, we try O(n) operations, each taking O(n) time to create and compare strings
โ Quadratic Growth
Space Complexity
O(n)
Space needed to store the generated strings during comparison
โก Linearithmic Space
Constraints
- 0 โค s.length, t.length โค 104
- s and t consist of lowercase English letters, digits, and/or space characters
- The strings may be empty
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code