thzinc

missingLetters - Interview question of the week from rendezvous with cassidoo

Simple, no-frills solution to this week’s question.

Interview question of the week

This week’s question: Write a function that takes an array of consecutive, increasing letters as input, and returns any missing letters in the array between the first and last letter.

Example:

> missingLetters(['a','b','c','d','f'])
> ['e']

> missingLetters(['a','b','c','d','e','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z'])
> ['f','g','v']

My solution

#mocha

  
function missingLetters(arr) {
  if (arr.length <= 1) return [];

  let [head, ...tail] = arr;
  let prev = head.charCodeAt(0);

  const result = [];
  for (const item of tail) {
    const curr = item.charCodeAt(0);
    for (let i = 1; i < curr - prev; i++) {
      result.push(String.fromCharCode(prev + i));
    }
    prev = curr;
  }
  return result;
}

mocha.setup("bdd");
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();

describe("Given the examples from the question", () => {
  const expectations = [
    {
      input: ["a", "b", "c", "d", "f"],
      output: ["e"],
    },
    {
      input: [
        "a",
        "b",
        "c",
        "d",
        "e",
        "h",
        "i",
        "j",
        "k",
        "l",
        "m",
        "n",
        "o",
        "p",
        "q",
        "r",
        "s",
        "t",
        "u",
        "w",
        "x",
        "y",
        "z",
      ],
      output: ["f", "g", "v"],
    },
  ];
  expectations.forEach(({ input, output }) => {
    it(`should return ${JSON.stringify(output)} for the input ${JSON.stringify(
      input
    )}`, () => {
      // Act
      const actual = missingLetters(input);

      // Assert
      Array.from(actual).should.deep.equal(output);
    });
  });
});

mocha.run();

See also