One Edit Distance - 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
sto gett - Delete exactly one character from
sto gett - Replace exactly one character of
swith a different character to gett
Input & Output
Example 1 — Insert Operation
$
Input:
s = 'ab', t = 'abc'
›
Output:
true
💡 Note:
We can insert 'c' at the end of 'ab' to get 'abc', which requires exactly one edit operation.
Example 2 — Replace Operation
$
Input:
s = 'cab', t = 'ad'
›
Output:
false
💡 Note:
Length difference is 2, which exceeds the maximum of 1 edit distance. No single edit can transform 'cab' to 'ad'.
Example 3 — Already Equal
$
Input:
s = 'abc', t = 'abc'
›
Output:
false
💡 Note:
The strings are already equal, so zero edits are needed, not exactly one edit.
Constraints
- 0 ≤ s.length, t.length ≤ 104
- s and t consist of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two strings s and t to compare
2
Check Edit Types
Try insert, delete, or replace operations
3
Output
Return true if exactly one edit transforms s to t
Key Takeaway
🎯 Key Insight: Use two pointers to find the first mismatch, then check if the remaining parts are identical after applying the appropriate edit operation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code