freeCodeCamp Algorithm Challenge Guide: Find the Longest Word in a String

freeCodeCamp Algorithm Challenge Guide: Find the Longest Word in a String
0

#1

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

:checkered_flag: Problem Explanation:

You have to go through each word and figure out which one is the longest and return not the word, but how many characters it has.

Relevant Links

:speech_balloon: Hint: 1

You should split the string into an array of words.

try to solve the problem now

:speech_balloon: Hint: 2

You will need to figure out a way to keep track of the greatest current length.

try to solve the problem now

:speech_balloon: Hint: 3

Remember how to get the length of elements on the array? Array[index].length.

try to solve the problem now

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solution ahead!

:beginner: Basic Code Solution:

function findLongestWord(str) {
  var words = str.split(' ');
  var maxLength = 0;

  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
    }
  }

  return maxLength;
}

:rocket: Run Code

Code Explanation:

Take the string and convert it into an array of words. Declare a variable to keep track of the maximum length and loop from 0 to the length of the array of words.

Then check for the longest word by comparing the current word to the previous one and storing the new longest word. At the end of the loop just return the number value of the variable maxLength.

Relevant Links

:sunflower: Intermediate Code Solution:

Using .reduce()

function findLongestWord(s) {
  return s.split(' ')
    .reduce(function(x, y) {
      return Math.max(x, y.length)
    }, 0);
}

:rocket: Run Code

Code Explanation:

For more information on reduce click here.

In case you’re wondering about that 0 after the callback function, it is used to give an initial value to the x, so that Math.max will know where to start.

Relevant Links

:rotating_light: Advanced Code Solution:

Using recursiveness

function findLongestWord(str) {

  //split the string into individual words 
  //(important!!, you'll see why later)
  str = str.split(" ");

  //str only has 1 element left that is the longest element, 
  //return the length of that element
  if(str.length == 1){
    return str[0].length;
  }

  //if the first element's length is greater than the second element's (or equal) 
  //remove the second element and recursively call the function)
  if(str[0].length >= str[1].length){
    str.splice(1,1);
    return findLongestWord(str.join(" "));
  }

  //if the second element's length is greater thant the first element's start 
  //call the function past the first element 
  if(str[0].length <= str[1].length){
    // from the first element to the last element inclusive.
    return findLongestWord(str.slice(1,str.length).join(" "));
  }
}

:rocket: Run Code

Code Explanation:

The first line splits the string into individual words. Then we check if str only has 1 element left then that is the longest element and we return it. If the first element’s length is greater than the second element’s (or equal), we remove the second element and recursively call the function findLongestWord. However, if the second element’s length is greater thant the first element’s start, then we call the function past the first element.

Relevant Links

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.


#2

#3

#5

The JS Math Max link in the intermediate function explanations returns-

{“errors”:[“The requested URL or resource could not be found.”],“error_type”:“not_found”}

It might just be to MDN anyway, but I didn’t know if it was a special FCC article.


#6

First ,when i use split(), I found str1 is a list, so , I just think why not get a list which contain every word’s length.
So I get a list of number, next problem is found the max number of the list, just google js max, so i get the solution.
I have compare my solution with official, my solution is not perfect ,but it’s a another way.
I feel happy with that.

`function findLongestWord(str) {
var str1 = str.split(" ");
var list = [];
for (i=0;i<str1.length;i++) {
list.push(str1[i].length) ;
}
return Math.max.apply(null ,list);
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);`


#8
function findLongestWord(str) {

return str.split(’ ').map(function(val){
return val.length;
}).sort(function(a, b){
return b - a;
})[0];

}

findLongestWord(“The quick brown fox jumped over the lazy dog”);


#9

This is my solution:

function findLongestWord(str) {
  
  var arr = str.split(" ");//split sentence to an array
  var longestWord = arr[0];//assume longest word is the first word of an array
  for (var i=0; i< arr.length; i++){ //iterate through array of words
    
    if(arr[i].length > longestWord.length){
      //compare other words of an array if they are longer than the first one
      longestWord = arr[i];
    }
  }
  return longestWord.length;//return length of the longest word
  
}
//test
findLongestWord("What if we try a super-long word such as otorhinolaryngology");

#10

Here is my take on a solution.

function findLongestWord(str) {
    return Math.max.apply(Math, str.split(' ').map(val = val => val.length));}

:slight_smile:


#11

Hi! I wanted to contribute with my solution :slight_smile:

function findLongestWord(str) {

  // Split the string into an array
  var array = str.split(" "); 

  // Then sort the array by its elements length, from longest to shortest
  array.sort(function(a,b) {
    return b.length - a.length; 
  });
  
  // Since the first element of the array will be the longest, then return the length of the first element
  return array[0].length; 
}

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

#12

Hi , i did it w/ sort function;

function findLongestWord(str) {
   var abc = str.split(" ");
   var newStr = [];
   for (var i = 0; i < abc.length; i++) {
   	
   	 newStr.push(abc[i].length);
   }
     var neweSTr= newStr.sort(function(x,y){return y -x;}); 	
   return neweSTr[0];
}

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


#13

Very short code; how you managed to simply write var longestWord in a such way in if condition ; Appreciate Really!! your logic;

      function findLongestWord(str) {

       var arr = str.split(" ");//split sentence to an array
       var longestWord = arr[0];//assume longest word is the first word of an array
       for (var i=0; i< arr.length; i++){ //iterate through array of words

if(arr[i].length > longestWord.length){
  //compare other words of an array if they are longer than the first one
  console.log(longestWord = arr[i]);
 }
 }
return //console.log(longestWord.length);//return length of the longest word
 
}
  //test
 findLongestWord("What if we try a super-long word such as otorhinolaryngology");

`
examining your code, where I have written console log in gives two strings, while should give just a lonestWord; Why could you explain me plz
Thanks ahead


#14

What is the advantage of the Advanced/ Intermediate Code over the Basic?


#15

Hi there! This is my solution.

function findLongestWord(str) {
      return str.split(" ").sort(function(a,b){
        return b.length - a.length;
      })[0].length;  
    }

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

:grin:


#16

Here is my take:slight_smile:
:slight_smile:

function findLongestWord(str) {
// Split the string into an array
var array = str.split(" ");
var lengths = array.map(function(word){
return word.length
})
var q = Math.max.apply(null, lengths);

return q

}`


#17

I really like the solutions using .reduce but I was wondering whether it is noticeably faster than the Basic Code Solution.


#18

function findLongestWord(str) {

var word = str.split(’ ');
var x = word[0].length;

for(i=0; i<word.length; i++){
if(word[i].length>x){
x = word[i].length;
}
}

return x;
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);


#19

My solution here i used the .toLowerCase() so when sorted, it would not put the capital string first but any comments on my solution would help thanks.

function findLongestWord(str) {
var strArry=[];

strArry=str.toLowerCase().split(’ ');
strArry.sort(function(a,b){
return b.length-a.length;
});

return strArry[0].length;
}

findLongestWord(“What if we try a super-long word such as otorhinolaryngology”);


#20

I managed to reach the basic solution, and looking at the hints am trying to do the advanced solution, but am encountering a “Type Error: str.splice is not a function” error message that for the life of me I can’t figure out. Can anyone explain my mistake? Code is below, but I also had an question about the intermediate solution:

function findLongestWord(str) {

if (!str.isArray) {
str.split(" ");}

if (str.length == 1) {
return str[0];
}

if (str[0].length >= str[1].length) {
str.splice(1,1);
return findLongestWord(str);
}

if (str[0].length <= str[1].length) {
str.splice(0,1);
return findLongestWord(str);
}

}
findLongestWord(“The quick brown fox jumped over the lazy dog”);

Regarding the intermediate solution, can someone please explain the logic behind function(x, y) {
return Math.max(x, y.length)
}

Thanks


#21

Hi @Alais29,

I did the exact same thing :slight_smile: .


#22

Why doesn’t this work?

var array = [];
function findLongestWord(str) {
  var newArray = str.split(" ");
  
  for (i = 0; i < newArray.length; i++) {
    var newLength = newArray[i].length;
    array = array.concat(newLength);
    
  }
  return array.reduce(function(previousValue, currentValue){
  return Math.max(previousValue,currentValue);
});
    
  
}

findLongestWord("May the force be with you");