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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay