DSA problem
One Edit Distance
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 edit distance apart from a string t if you can convert s to t (or t to s) with exactly one of the following operations:
- 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.
Note that two identical strings are zero edits apart, not one, so the function must return false in that case. The operation count must be exactly one, no more and no fewer.
Examples
Example 1
Input:
s = "ab", t = "acb"Output:
trueExplanation: We can insert the character "c" into s to get t, which is exactly one edit.
Example 2
Input:
s = "cab", t = "ad"Output:
falseExplanation: We cannot convert s to t with only one edit; the strings differ too much.
Example 3
Input:
s = "abc", t = "abc"Output:
falseExplanation: The strings are identical, so they are zero edits apart, not one.
Constraints
- 0 <= s.length, t.length <= 10^4
- s and t consist of lowercase letters, uppercase letters, and digits.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.