Finding the Longest Word in a String Challenge:


  Return the length of the longest word in the provided sentence.


I've made a solution that works but it is kinda bad since the time complexity is \$O(n \log n)\$ and it involves mutation.

function findLongestWordLength(str) {
  let strSplit = str.split(" ");
  let wordLengthArray = [];
  for(let i = 0; i &lt; strSplit.length; i++)
  {
    wordLengthArray.push(strSplit[i].length);
  }
  wordLengthArray.sort(function(a , b){return a - b});
  return wordLengthArray[wordLengthArray.length - 1];
}


I basically split the string, pushed all the word lengths in an empty array, then used the ascending sort function. After that I returned the last index of the new array which is the longest length.

Test Cases:

findLongestWordLength("The quick brown fox jumped over the lazy dog") should return 6.
findLongestWordLength("May the force be with you") should return 5.
findLongestWordLength("Google do a barrel roll") should return 6.
findLongestWordLength("What is the average airspeed velocity of an unladen swallow") should return 8.
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19.


I would appreciate some hints/tips on a better algorithm.
You are creating an array of strings (using str.split(" ")) as well as an array of numbers (wordLengthArray), then sorting wordLengthArray.  All three of those operations are wasteful, if you are aiming for performance.



function findLongestWordLength(str) {
  let maxLen = -1;
  for (var i = 0, j; (j = str.indexOf(" ", i)) != -1; i = j + 1) {
    maxLen = Math.max(maxLen, j - i);
  }
  return Math.max(maxLen, str.length - i);
}

console.log(6 == findLongestWordLength("The quick brown fox jumped over the lazy dog"));
console.log(5 == findLongestWordLength("May the force be with you"));
console.log(6 == findLongestWordLength("Google do a barrel roll"));
console.log(8 == findLongestWordLength("What is the average airspeed velocity of an unladen swallow"));
console.log(19 == findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"));




Depending on the browser/interpreter, your function is 33% to 86% slower than mine.