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 INPUT String s: a b idx: 0 idx: 1 String t: a b c idx: 0 idx: 1 idx: 2 Input Values s = "ab" (len = 2) t = "abc" (len = 3) ALGORITHM STEPS 1 Check Lengths |len(s) - len(t)| must be <= 1, else return false 2 Compare Characters Iterate both strings until mismatch found 3 Handle Mismatch Insert: skip char in t Delete: skip char in s Replace: skip both 4 Verify Remaining Rest of strings must match exactly Length Check |2 - 3| = 1 <= 1 OK - Proceed! FINAL RESULT Character Comparison: a = a OK b = b OK -- ! c INSERT Edit Type: INSERT Insert 'c' at end of s Output true Key Insight: The optimal solution runs in O(n) time by comparing characters until a difference is found. For INSERT/DELETE: length difference must be exactly 1. For REPLACE: lengths must be equal. After handling one edit, remaining substrings must match exactly for the answer to be true. TutorialsPoint - One Edit Distance | Optimal Solution O(n)
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