One Edit Distance — LeetCode 161 Python Solution
- Problem
- #161
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
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 + 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(m), where m is the length of string s |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 161. One Edit Distance is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 161. One Edit Distance?
- LeetCode 161. One Edit Distance is rated Medium on LeetCode.
- What is the time complexity of LeetCode 161. One Edit Distance?
- The Python solution on this page runs in O(m), where m is the length of string s.
- What is the space complexity of LeetCode 161. One Edit Distance?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 161. One Edit Distance cover?
- LeetCode 161. One Edit Distance is tagged Two Pointers and String on LeetCode.
- Is LeetCode 161. One Edit Distance a premium problem?
- Yes. LeetCode 161. One Edit Distance is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.