DEV Community

Cover image for Codewars - Find the missing letter
Nicolás Bost
Nicolás Bost

Posted on

Codewars - Find the missing letter

Salutations.

Gopher says hi

I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.

For this next exercise we have an ordered, ascending array of letters, but somewhere in the middle one letter is missing:
['a','b','c','d','f']
['O','Q','R','S']

First, we need to know that letters have a corresponding numerical value in Unicode. Therefore, we need functions capable of transforming letters to numbers and vice versa.

Let's try some JS functions to see what they do:

function findMissingLetter(array)
{
  return [array[3].charCodeAt(),array[4].charCodeAt()];
}

// the array is ['a','b','c','d','f']
// it expects 'e'
// this function returns [ 100, 102 ]
Enter fullscreen mode Exit fullscreen mode

We have our first important piece of the puzzle. Now we need to create a solution around it. To do so, we could use something to traverse the array, looking for the anomaly:

let counter = 0;
  while (array[counter].charCodeAt() + 1 == array[counter + 1].charCodeAt()
        && counter < array.length)
  {
    counter++;
  }
Enter fullscreen mode Exit fullscreen mode

Then, we need to find the actual missing letter:

let letter = String.fromCharCode(array[counter].charCodeAt() + 1)
Enter fullscreen mode Exit fullscreen mode

Assemble everything:

function findMissingLetter(array)
{
  let counter = 0;
  while (array[counter].charCodeAt() + 1 == array[counter + 1].charCodeAt()
        && counter < array.length)
  {
    counter++;
  }
  let letter = String.fromCharCode(array[counter].charCodeAt() + 1)
  return letter;
}
Enter fullscreen mode Exit fullscreen mode

Surprisingly readable. I think it's fine. There has to be a way to optimize it, but I can't see how yet.

Take care. Drink water 💧💧💧.

Previous

Top comments (0)