Find the first recurring letter in a string – Javascript Coding Question

Next in our series of Javascript Coding Questions comes a question that may seem confusing at first. The challenge is as follows:

 

The function:

 

“Build a function that takes in one parameter: a String; This function will then return the first letter that appears repeatedly in this string.”

 

Solution (In Javascript):

 

There are many approaches to addressing this problem. One that I found effective was to first convert the String parameter into an array, then iterating through this Array.

  1. To convert the string into an array, we use Array.from

    let array = Array.from(string);

    For instance, the given string “BBA” will be converted into the array [‘B’,’B’,’A’].

  2. Here comes the magical part. For each letter, we will search the array again for the same letter. But, we must find it in a different index(position in the array).
    let retVal = array.find((character, index) => {
      return array.indexOf(character) < index;
    });

    Array.find will return the current element in the iteration if the testing function returns true. So in the testing function we can verify, using Array.indexOf, if the current letter has appeared before in the Array. When this becomes trueArray.find will return the letter, as stated above.

Full working example:

let firstRecurringCharacter = string => {
  let array = Array.from(string);
  let recurringCharacter = array.find((character, index) => {
    return array.indexOf(character) < index;
  });

  let output =
    recurringCharacter ? recurringCharacter : "No recurring character";

  /**
   *	Using document.write so you can see the output
   *  without opening the console 😉
   */
  document.write(output + "<br>");
}

firstRecurringCharacter('ABCA');
firstRecurringCharacter('BCABA');
firstRecurringCharacter('ABC');

Disclaimer: No interview is ever the same, so be ready for variations !

Share your thoughts