Problem Description
Given two strings s and t, determine if they are exactly one edit operation apart. An edit operation is defined as inserting exactly one character, deleting exactly one character, or replacing exactly one character in s to obtain t.
Key Insights
- The difference in length between s and t must be at most 1.
- When lengths are equal, the only possibility is that exactly one character is different (replacement).
- When one string is longer by one character, the difference can be fixed by one insertion (or deletion in the other direction).
- Use two pointers to compare corresponding characters and carefully handle the first difference.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the shorter string, as we traverse both strings at most once. Space Complexity: O(1), using only constant extra space.
Solution
The solution uses a two-pointer approach. First, we check if the length difference is greater than 1, in which case they cannot be one edit apart. For the two primary cases:
- When strings are of equal length, iterate through both strings and count the number of differing characters. There should be exactly one difference.
- When lengths differ by one, use pointers for both strings. Upon encountering a difference, increment the pointer for the longer string only and ensure that no previous difference has been encountered. If a second discrepancy is found, return false. The key is to handle the edge case where the difference is at the end of the string.