One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart. One ediit distance means doing one of these operation:

  • insert one character in any position of S

  • delete one character in S

  • change one character in S to other character

Example

Example 1:

Input: s = "aDb", t = "adb" 
Output: true

Example 2:

Input: s = "ab", t = "ab" 
Output: false
Explanation:
s=t ,so they aren't one edit distance apart
public class Solution {
    public boolean isOneEditDistance(String s1, String s2) {
        int m = s1.length(), n = s2.length();
        if (Math.abs(m - n) > 1)
            return false;
        int count = 0; // Count of edits
        int i = 0, j = 0;
        while (i < m && j < n) {
            // If current characters don't match
            if (s1.charAt(i) != s2.charAt(j)) {
                if (count == 1)
                    return false;

                // If length of one string is more, then possible edits
                // are 1-> Add a character 2-> Remove a character
                // If we add to smaller string OR remove from bigger string
                // in both the cases the pointer of bigger string needs to move
                if (m > n)
                    i++;
                else if (m < n)
                    j++;
                // If m==n, then only possible edit is to replace char
                // In this both the pointers will move ahead
                else {
                    i++;
                    j++;
                }

                // Increment count of edits
                count++;
            } else {
                i++;
                j++;
            }
        }
        // If we reach here and m & n have not reached full lengths
        // That means the strings are equal upto min(m,n) (maybe with 1 edit already)
        // So now to make these 2 equals, we can add the extra char to smaller string
        if (i < m || j < n)
            count++;

        return count == 1;
    }
}

Last updated