2dbi

Check if two strings differ by at most one character

viaLeetCode

Problem Determine whether two strings are "equal within one character" — identical, or fixable by exactly one substitution, insertion, or deletion (edit distance <= 1).

Input / Output

  • Input: strings a, b. Output: boolean.

Constraints

  • Lengths up to 10^5; O(n) single pass expected — full edit-distance DP is overkill and says so.

Example

  • "cat"/"cut" → true (substitution); "cat"/"cats" → true (insertion); "cat"/"dog" → false; length gap ≥ 2 → false immediately.

Expected approach

  • Case split on length difference: (a) equal lengths → scan counting mismatches, fail past 1; (b) lengths differ by 1 → two pointers on both strings, allow ONE skip on the longer string at the first mismatch, then require exact match; (c) difference ≥ 2 → false. O(n)/O(1). Edge discipline: mismatch at the very end, empty strings, identical strings (decide if "zero edits" qualifies — clarify "at most" vs "exactly" one). This check is the primitive inside spell-correction / One Edit Distance (LC 161).
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account