Coding Challenge – One Edit Boolean. Write a function to return if two words are exactly “one edit” away.

Please follow & like us :)

Write a function to return if two words are exactly “one edit” away. where an edit can be inserting one character anywhere in the word or removing one character or replacing exactly one character

Here are the examples:

Lets say if you have input strings like shown in the example here 
 
input str1 = 'payal' 
input str2 = 'paypal'

So after comparing both inputs, you can say if you either add one character to input str1 or remove one character from input str2, both strings will be identical.

Output will be true. 

To solve this problem we have to compare characters side by side of both strings. If there is any miss match you can add the counter. If counter is greater than 1 we can return false otherwise it will be true.
Here is the Actual code which compares two strings for one edit away.

function oneEditBool(s1, s2) {
    let countDiff = 0;
    let i = 0;
    let j = 0;
    let length = Math.abs(s1.length - s2.length);
    if (length > 1) return false;
    let initlength = (s1.length > s2.length) ? s1.length : s2.length;
    while (i < initlength && j < initlength) {
        if (s1[i] !== s2[j]) {
            countDiff++;
            if (s1.length > s2.length) {
                i++;
                break;
            }
            else if (s1.length < s2.length) {
                j++;
                break;
            }
        }
        i++; j++;
    }
    return (countDiff === 1) ? true : false;
}
console.log(oneEditBool('same', 'smey'));