One Edit Distance — LeetCode 161 Python Solution

MediumLeetCode PremiumTwo PointersString
Problem
#161
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(m), where m is the length of string s
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview