Be Brav3

FCC: Missing Letters (JavaScript Intermediate Algorithm)

September 22, 2016

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

[js]

function fearNotLetter(str) {

return str;

}

fearNotLetter(“abce”);

[/js]

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.

[js]

for (let x = 0; x < str.length; x += 1) {

charCode.push(str.charCodeAt(x));

}

[/js]

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.

[js]

for (let y = 0; y < charCode.length – 1; y += 1) {

currentCode = charCode[y];

nextCode = charCode[y + 1];

if (currentCode + 1 !== nextCode) {

missingCode = currentCode + 1;

}

}

[/js]

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.

[js]

if (missingCode !== undefined) {

str = String.fromCharCode(missingCode);

} else {

str = undefined;

}

[/js]

The full code is below:

[js]

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’);

[/js]