One Edit Distance
Medium
Topics
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
true.Input: s = "ab", t = "acb" Output: true Explanation: Inserting c into s gives t.
Example 2
false.Input: s = "cab", t = "ad" Output: false Explanation: Reaching t from s needs more than one edit.
Example 3
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
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
- If the lengths differ by more than one, return
false. - Arrange it so
sis the shorter string (or equal), by swapping if needed. That removes the mirror-image case. - 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
trueonly if the longer one has exactly one character left over. - 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 falseComplexity
- 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
truefor 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
sis 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) + 1import java.util.*;
class Solution {
public boolean isOneEditDistance(String s, String t) {
if (Math.abs(s.length() - t.length()) > 1) return false;
if (s.length() > t.length()) {
String tmp = s;
s = t;
t = tmp;
}
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == t.charAt(i)) continue;
if (s.length() == t.length()) return s.substring(i + 1).equals(t.substring(i + 1));
return s.substring(i).equals(t.substring(i + 1));
}
return t.length() == s.length() + 1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isOneEditDistance(string s, string t) {
if (abs((int)s.size() - (int)t.size()) > 1) return false;
if (s.size() > t.size()) swap(s, t);
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == t[i]) continue;
if (s.size() == t.size()) return s.substr(i + 1) == t.substr(i + 1);
return s.substr(i) == t.substr(i + 1);
}
return t.size() == s.size() + 1;
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var isOneEditDistance = function(s, t) {
if (Math.abs(s.length - t.length) > 1) return false;
if (s.length > t.length) {
const tmp = s;
s = t;
t = tmp;
}
for (let i = 0; i < s.length; i++) {
if (s[i] === t[i]) continue;
if (s.length === t.length) return s.slice(i + 1) === t.slice(i + 1);
return s.slice(i) === t.slice(i + 1);
}
return t.length === s.length + 1;
};