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 s to get t
  • Delete exactly one character from s to get t
  • Replace exactly one character of s with a different character to get t

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
One Edit Distance: Three Operations1. Insert Operation'ab' → 'abc'Insert 'c' at end2. Delete Operation'abc' → 'ab'Delete 'c' from end3. Replace Operation'abc' → 'abd'Replace 'c' with 'd'Algorithm Check1. Length difference ≤ 1?2. Scan with two pointers3. On mismatch, try appropriate editReturn true if exactly one edit needed
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
Asked in
Google 15 Facebook 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen