159/670

159. One Edit Distance

Medium

You are given two strings s and t. Decide whether s is exactly one edit away from t, and return true or false.

A single edit is one of:

  • insert one character anywhere in s,
  • delete one character from s,
  • replace one character of s with a different character.

Identical strings are zero edits apart, so they must return false. Either string may be empty.

Can you decide it in one pass, without building any candidate strings?

Example 1:

Input: s = "teach", t = "peach"

Output: true

Explanation: Replacing the leading 't' with a 'p' turns "teach" into "peach" — a single replacement.

Example 2:

Input: s = "code", t = "code"

Output: false

Explanation: The strings already match. Zero edits is not one edit.

Example 3:

Input: s = "ab", t = "acb"

Output: true

Explanation: Inserting a 'c' between 'a' and 'b' produces "acb".

Constraints:

  • 0 ≤ s.length, t.length ≤ 10⁴
  • s and t consist of lowercase English letters and digits.

Hints:

If the two lengths differ by more than one, no single edit can close the gap — answer false immediately.

Walk both strings in lockstep until the first index where they disagree. Everything after that point is forced: there is no freedom left about where the edit happens.

At the first mismatch: equal lengths force a replacement (compare both suffixes after skipping one char each); a length gap of one forces an insert/delete (skip one char in the longer string only). If you never mismatch, the answer is true exactly when the lengths differ by one.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "teach", t = "peach"

Expected output: true