Leetcode #161: One Edit Distance
In this guide, we solve Leetcode #161 One Edit Distance in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Two Pointers, String
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.
Python Solution
class Solution:
def isOneEditDistance(self, s: str, t: str) -> bool:
if len(s) < len(t):
return self.isOneEditDistance(t, s)
m, n = len(s), len(t)
if m - n > 1:
return False
for i, c in enumerate(t):
if c != s[i]:
return s[i + 1 :] == t[i + 1 :] if m == n else s[i + 1 :] == t[i:]
return m == n + 1
Complexity
The time complexity is , where is the length of string . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.