Basic Algorithm Scripting - Find the Longest Word in a String

Tell us what’s happening:
All the test cases except for findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")
What am I doing wrong here ?

Your code so far

function findLongestWordLength(str) {
  let count=0;
  let arr=[];
  for(let i=0;i<str.length;i++){
    if(str[i]!=' '){
      count+=1;
    }
    else{
      arr.push(count);
      count=0;
    }
  }
  let big=arr[0];
  for(let j=0;j<arr.length;j++){
    if(big<arr[j]){
      big=arr[j];

    }


  }

  return big;
}

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

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

Link to the challenge:

this part.

if(str[i]!=’ '){
count+=1;
}
else{
arr.push(count);
count=0;
}

For the last test. Your if-else logic could not catch the otorhinolaryngology.
It could not see a " " , thus did not return its length.
i suggest u add line of console.log(‘’) at bottom of the logic for easier debugging

I don’t understand why it’s not catching the ’ ’ before otorhinolaryngology and why if-else is failing here when it’s working everywhere else.

Because the last character of the whole string is " y ".

Not a empty space " "

It is cool you solve it this way.
Alternatively and easily, you can solve it with string.length approach.

I learnt a lot from the Get help → Get a Hint section.

1 Like

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