Find the Longest Word in a String - Using Insertion sort

Hi Guys,

I tried solving this challenge using insertion sort.

The code below works well for all the test cases except “What if we try a super-long word such as otorhinolaryngology”

Where it returns 4 as the output instead of 19. Can you guys help me understand the problem here ? Also I am new to this stuff, so I request you to please dumb down your answers so that I can understand :slight_smile:

function findLongestWord(str){
  
var arr =[]; 
arr = str.split(" ");

var arr2 = [];
for (var s=0;s<arr.length;s++){
  arr2[s] = arr[s].length;
}
for(var i=1; i<arr2.length;i++){
 
  var key = arr2[i];
  var j = i-1;
  while(j>=0 && arr2[j]< key){
    arr2[j+i] = arr2[j];
    j = j-1;
  }
  
  arr2[j+1] = key;
  
  
}

return arr2[0];
}

If I’m not mistaken you are trying to compare every number in the array, starting from index = 1, with every number before it to see if they are larger—but whatever you are doing inside the while loop doesn’t quite make sense.

Using the input "What if we try a super-long word such as otorhinolaryngology", your code is actually producing undefined in arr2 because j + 1 becomes larger than arr.length at some point (which I suspect isn’t what you want). In fact, if you console.log(arr2) inside, and at the end of, the while loop, you will see that 19 (the length for otorhinolaryngology) gets overwritten at some point, too.

I suggest that you write down step by step the logic that you want for the second for loop and implement it again once you are happy with the logic.

Good luck!