There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
Example 1:
Input:
first = "pale"
second = "ple"
Output: True
Example 2:
Input:
first = "pales"
second = "pal"
Output: False
Solutions
Solution 1: Case Analysis + Two Pointers
Thinking
One edit is a replace, insert, or delete. Enumerating every one-edit neighbor of the shorter string is linear in length but clumsy to implement.
A length gap greater than \(1\) cannot be bridged by one edit. Assume \(m \ge n\): equal lengths allow exactly one replacement; a gap of \(1\) means the longer string has exactly one extra character.
On equal length, count mismatches; otherwise two pointers skip at most one mismatch on the longer string. Swapping so the first argument is longer implements only the delete case.
Let the lengths of the strings \(\textit{first}\) and \(\textit{second}\) be \(m\) and \(n\), respectively. Assume \(m \geq n\).
Next, we discuss the following cases:
When \(m - n \gt 1\), \(\textit{first}\) and \(\textit{second}\) cannot be made equal with one edit, so return false;
When \(m = n\), \(\textit{first}\) and \(\textit{second}\) can be made equal with one edit only if there is exactly one different character;
When \(m - n = 1\), \(\textit{first}\) and \(\textit{second}\) can be made equal with one edit only if \(\textit{second}\) is obtained by deleting one character from \(\textit{first}\). We can use two pointers to achieve this.
The time complexity is \(O(n)\), where \(n\) is the length of the string. The space complexity is \(O(1)\).