One Edit Distance - Problem
One Edit Distance

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 s

Return 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
One Edit Distance: Document ComparisonDocument A: "Hello World"Hello WorldDocument B: "Hello world"Hello worldAnalysisโœ“ First 6 characters matchโœ— Difference at position 6: 'W' vs 'w'โœ“ Same length โ†’ REPLACE operationโœ“ Remaining characters match๐ŸŽฏ Key InsightOne edit distance means exactly one character operation.Find first mismatch, determine edit type, verify remainder matches.
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

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space needed to store the generated strings during comparison

n
2n
โšก 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
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28 Apple 22
42.3K Views
High Frequency
~25 min Avg. Time
1.9K 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