codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Cracking The Coding Interview] 1.5: One Away #10

Open jtkaufman737 opened 5 years ago

jtkaufman737 commented 5 years ago

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
pale, pa le -> true
jtkaufman737 commented 5 years ago

https://repl.it/@jtkaufman737/AllBewitchedBooleanvalue

function testsOneAway(strOne, strTwo){
  let irregularities = 0; 
  strOne = Array.from(strOne), strTwo = Array.from(strTwo);
  let shortString = strOne, longString = strTwo;

  if(strOne.length > strTwo.length){
    shortString = strTwo;
    longString = strOne;
  } 

  for(let i=0; i < shortString.length; i++) {
    if(irregularities < 2) {

      // handle same length 
      if(strOne.length == strTwo.length) {
        if(strOne[i] !== strTwo[i]) {
          irregularities += 1;
        } 
      } else { // handle uneven length
        if(shortString[i] != longString[i]) {
         irregularities += 1;
         longString.splice(i,1);   
       }
      }
    } else {
      break;
    }
  }

  if(irregularities < 2) {
    console.log("Great, you passed the one-away test!");
  } else {
    console.log("Sorry, these failed the one-away test")
  }

}

testsOneAway("pale","patt"); // should fail 
testsOneAway("pale","ple") // should pass 
testsOneAway("pale","bake") // should fail
testsOneAway("cake","bake") //should pass 
testsOneAway("pa le","pale") // should pass