Basic Algorithm Scripting - Find the Longest Word in a String

Tell us what’s happening:
Alright so, first of all I want to say that I know that this code is way more complex than it needs to be. I usually just try to brute force these problems until I get the right answer then I refine and simplify my code.

Anyway, when I run this code on it works for “The quick brown fox…” and returns the correct number. When I run it with any of the other provided values of str I get “Uncaught RangeError: Invalid array length” on line 17 (index++;). Is anyone able to explain why?

Further, I am unable to run this code on fCC itself because it times out, is this just because there’s too much recursion happening?

Thanks in advance.

Your code so far

function findLongestWordLength(str) {
  let myArr = [...str];
  let myArr2 = [];
  let myArr3 = [];
  let length = 0;
  let index = 0;
  for (let i = 0; i < myArr.length; i++) {
    for (let j = index; myArr[j] != " "; j++) {
      if (myArr2.length > length) {
        length = myArr2.length;
        myArr3 = myArr2;
        myArr2 = [];
      } else {
        myArr2 = [];
    str = "";
    for (let i = 0; i <myArr3.length; i++) {
      str += myArr3[i];
  return str.length;

findLongestWordLength("The quick brown fox jumped over the lazy dog");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36 Edg/110.0.1587.50

Challenge: Basic Algorithm Scripting - Find the Longest Word in a String

Link to the challenge:

Basically, your function is doing so much work that the infinite loop protection is stopping it early. You have the right basic idea, but you have coded it up in a way that’s much slower than it needs to be and this is causing the tests to fail.

For your first loop over i, do you want to visit every single letter or every single word?

This loop condition will have an issue because not every word ends with a space!

Also, the variable names myArr, myArr2, and myArr3 make it really hard to follow what you mean this code to represent. Some clearer names would really help other people understand and help.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.