One Edit Distance

Medium

Topics
Two PointersString

Given two strings s and t, return true if they are exactly one edit distance apart.

One edit means one of: insert exactly one character into s to get t; delete exactly one character from s to get t; or replace exactly one character of s with a different character to get t.

Exactly one. Two identical strings are zero edits apart, so they return false.

Example 1

sa0b1
ta0c1b2
where the one edit would go
Lengths differing by one leave insertion as the only possible edit. The first difference is at index 1 of the longer string, and dropping that one character leaves the shorter string exactly, so the answer is true.
One cell per character; the small numbers underneath are indices.
Input:  s = "ab", t = "acb"
Output: true
Explanation: Inserting c into s gives t.

Example 2

sc0a1b2
ta0d1
where the one edit would go
The first difference is at index 0 of the longer string, and dropping that one character still does not leave the shorter string, so the answer is false.
Input:  s = "cab", t = "ad"
Output: false
Explanation: Reaching t from s needs more than one edit.

Example 3

sa0b1c2
ta0b1c2
The two strings are identical, so they are zero edits apart. The question asks for exactly one, which makes the answer false — this is the case most solutions get wrong.
Input:  s = "abc", t = "abc"
Output: false
Explanation: Identical strings are zero edits apart, not one.

Example 4

s
empty string
tA0
where the one edit would go
The shorter string is a prefix of the longer one, so there is no differing character anywhere. The only difference is the 1 character hanging off the end, making the answer true.
Input:  s = "", t = "A"
Output: true
Explanation: Inserting a single character into the empty string is one edit.

Constraints

  • 0 <= s.length, t.length <= 10^4
  • s and t consist of lowercase letters, uppercase letters and digits
Editorial — intuition, approach, complexity and pitfalls

Intuition

Computing the full edit distance and comparing it to 1 is enormous overkill. The budget of one edit is so tight that the lengths alone rule out almost everything: if they differ by 2 or more the answer is false immediately, because one edit changes the length by at most one.

That leaves two shapes. Equal lengths means the only possible edit is a replacement, so the strings must match everywhere except one position. Lengths differing by exactly one means the only possible edit is an insertion, so the shorter string must be the longer one with one character removed.

Both shapes collapse into a single scan: walk until the first mismatch, then check that what follows lines up under the one edit being spent. There is nothing to backtrack over, because a single budget means there is only ever one place to spend it.

Approach

  1. If the lengths differ by more than one, return false.
  2. Arrange it so s is the shorter string (or equal), by swapping if needed. That removes the mirror-image case.
  3. Scan both from the left to the first index where the characters differ. If no such index exists, the strings agree as far as the shorter one goes — return true only if the longer one has exactly one character left over.
  4. At the mismatch, spend the edit. If the lengths are equal, the rest of both strings must match from the next index. If they differ by one, the rest of the longer string from the next index must match the rest of the shorter from the same index.

Walkthrough

s = "ab", t = "acb"

lengths 2 and 3, differ by one -> insertion case
s is shorter already

i=0   s[0]=a   t[0]=a   match
i=1   s[1]=b   t[1]=c   mismatch, spend the edit

insertion case: compare s from i with t from i+1
  s[1:] = "b"      t[2:] = "b"     equal

answer true

---

s = "abc", t = "abc"

equal lengths, scan finds no mismatch.
Nothing left over in either string, so no edit was
spent at all -> answer false

Complexity

  • Time — O(n): one scan to the mismatch and one comparison of the remainders, each at most the length of the shorter string.
  • Space — O(1): only indices, if the remainder comparison is done by scanning rather than by slicing. Slicing as written above costs O(n).

Common Pitfalls

  • Returning true for identical strings. The word is exactly one edit, and zero does not qualify — this is the single most common wrong answer here.
  • Handling only the case where s is shorter. Without the swap, s = "acb", t = "ab" falls through the insertion branch backwards.
  • In the insertion case, advancing both indices past the mismatch. Only the longer string’s index moves; the shorter one’s character still has to be matched.
  • Forgetting the no-mismatch path, where the shorter string is a prefix of the longer. s = "ab", t = "abc" never hits a differing character.

Full Solution — all languages

class Solution:
    def isOneEditDistance(self, s, t):
        if abs(len(s) - len(t)) > 1:
            return False
        if len(s) > len(t):
            s, t = t, s                 # s is now the shorter (or equal) one
        for i in range(len(s)):
            if s[i] == t[i]:
                continue
            # First mismatch. Compare the tails by index rather than slicing --
            # s[i+1:] == t[i+1:] copies both tails and costs O(n) space.
            if len(s) == len(t):
                # substitution: the rest must match position for position
                return all(s[k] == t[k] for k in range(i + 1, len(s)))
            # insertion: t has one extra character here, so s[i:] aligns with t[i+1:]
            return all(s[k] == t[k + 1] for k in range(i, len(s)))
        # no mismatch in the shared prefix: equal lengths means identical strings,
        # which is zero edits, not one
        return len(t) == len(s) + 1
SensAI
Beta
Tap the mic to stop voice mode