FCC: Missing Letters (JavaScript Intermediate Algorithm)

In FCC challenge Missing Letters we’re tasked with finding the missing letter in a string of sorted alphabets:

function fearNotLetter(str) {
  return str;
}

fearNotLetter("abce");

First we need to convert the string of alphabets to their UTF-16 unicode equivalent using the charCodeAt function. Then store the unicode in an array for comparison.

for (let x = 0; x < str.length; x += 1) {
  charCode.push(str.charCodeAt(x));
}

Once the unicode values are stored in the array we can now compare each element of the array to its neighbor element. If any left neighbor element is not one less or any right neighbor element is not one more, then we have located the area of the missing unicode. We then store the missing unicode for conversion back to the equivalent alphabet.

for (let y = 0; y < charCode.length - 1; y += 1) {
  currentCode = charCode[y];
  nextCode = charCode[y + 1];

  if (currentCode + 1 !== nextCode) {
    missingCode = currentCode + 1;
  }
}

In the final step we assign str variable with the converted unicode alphabet if the missingCode variable is not undefined. Otherwise we update str variable with undefined. Finally returning the updated str variable back to the calling function.

if (missingCode !== undefined) {
  str = String.fromCharCode(missingCode);
} else {
  str = undefined;
}

The full code is below:

function fearNotLetter(str) {
  const charCode = [];
  let currentCode;
  let nextCode;
  let missingCode;

  for (let x = 0; x < str.length; x += 1) {
    charCode.push(str.charCodeAt(x));
  }

  for (let y = 0; y < charCode.length - 1; y += 1) {
    currentCode = charCode[y];
    nextCode = charCode[y + 1];

    if (currentCode + 1 !== nextCode) {
      missingCode = currentCode + 1;
    }
  }

  if (missingCode !== undefined) {
    str = String.fromCharCode(missingCode);
  } else {
    str = undefined;
  }
  console.log(str);
  return str;
}

fearNotLetter('abce');
fearNotLetter('abcdefghjklmno');
fearNotLetter('bcd');
fearNotLetter('yz');

Leave a Comment