DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

One Away: Replace, add, remove

One Away: 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
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bake -> false

Observe that you don't need to check the strings for insertion, removal, and replacement edits. The lengths
of the strings will indicate which of these you need to check.

const oneWay = (str1, str2) => {
  // check which function
  if (str1.length === str2.length) {
    return oneEditReplace(str1, str2);
  } else if (str1.length + 1 == str2.length) {
    return oneEditinsert(str1, str2);
  } else if (str1.length - 1 == str2.length) {
    return oneEditinsert(str2, str1);
  }
};

const oneEditReplace = (s1, s2) => {
  let foundDifference = false;
  for (let i = 0; i < s1.length; i++) {
    if (s1.charAt(i) != s2.charAt(i)) {
      if (foundDifference) {
        return false;
      }
      foundDifference = true;
    }
  }
  return foundDifference;
};

const oneEditinsert = (s1, s2) => {
  let indexl = 0;
  let index2 = 0;
  while (index2 < s2.length && indexl < s1.length) {
    if (s1.charAt(indexl) != s2.charAt(index2)) {
      if (indexl != index2) {
        return false;
      }
      index2++;
    } else {
      indexl++;
      index2++;
    }
  }
  return true;
};

console.log(oneWay("bal", "bale"));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)