Coderbyte – Letter Count – Code challenge – JavaScript Solution Source Code Answers

Coderbyte – Letter Count

Have the function LetterCount(str) take the str parameter being passed and return the first word with the greatest number of repeated letters. For example: “Today, is the greatest day ever!” should return greatest because it has 2 e’s (and 2 t’s) and it comes before ever which also has 2 e’s. If there are no words with repeating letters return -1. Words will be separated by spaces.

function LetterCount(str) { 

const words = str.split(' ');
let maxWord = '';
let maxCount = 1;

for (let i = 0; i < words.length; i++) {
  const counts = {};
  let count = 0;
  for (let j = 0; j < words[i].length; j++) {
    const char = words[i][j];
    counts[char] = counts[char] ? counts[char] + 1 : 1;
    if (counts[char] > count) {
      count = counts[char];
    }
  }
  if (count > maxCount) {
    maxCount = count;
    maxWord = words[i];
  }
}

return maxWord || -1;
}
   
// keep this function call here 
console.log(LetterCount(readline()));

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *