Problem Statement
Find the longest word in a sentence.
Example Inputs
- Input: "The quick brown fox"
- Input: "JavaScript is awesome"
- Input: "OpenAI creates AI solutions"
- Input: "Learning coding is fun"
JavaScript Method - Using Only String Methods
Approach
To find the longest word in a sentence, we can split the sentence into words and then find the word with the maximum length.
Steps
- Use .split(' ')to split the sentence into an array of words.
- Initialize a variable to track the longest word.
- Loop through the array of words, comparing each word's length to the current longest word.
- If a word is longer than the current longest word, update the longest word.
- Return the longest word.
Time & Space Complexity
- Time Complexity: O(n), where n is the total number of characters in the sentence, as we process each character once.
- Space Complexity: O(m), where m is the number of words, due to storing words in an array.
Code Snippet
Dry Run
Example input: "The quick brown fox"
- Step 1: sentence.split(' ')→['The', 'quick', 'brown', 'fox']
- Step 2: Initialize longestWord = ""
- Loop through words:
- Compare "The"→ Longest word is"The"
- Compare "quick"→ Longest word is"quick"
- Compare "brown"→ Longest word is"quick"
- Compare "fox"→ Longest word remains"quick"
 
- Final output: "quick"
Alternative Approach - Using Reduce Function
Approach
We can also use the reduce function to find the longest word in a sentence by comparing each word's length.
Steps
- Use .split(' ')to split the sentence into an array of words.
- Use .reduce()to iterate over words and keep track of the longest word based on length.
Time & Space Complexity
- Time Complexity: O(n), as each character is processed once.
- Space Complexity: O(m), where m is the number of words in the array.
Code Snippet
Dry Run
Example input: "The quick brown fox"
- Step 1: sentence.split(' ')→['The', 'quick', 'brown', 'fox']
- Step 2: Use .reduce()to compare word lengths:
- Compare "The"→ Longest is"The"
- Compare "quick"→ Longest is"quick"
- Compare "brown"→ Longest is"quick"
- Compare "fox"→ Longest remains"quick"
 
- Final output: "quick"
Complexity Analysis
JavaScript Method (Using String Methods)
- Time Complexity: O(n)
- Space Complexity: O(m)
Alternative Approach (Using Reduce)
- Time Complexity: O(n)
- Space Complexity: O(m)
Conclusion
Finding the longest word in a sentence can be achieved by splitting the sentence into words and iterating through them. Using either a loop or the reduce function provides an efficient solution, with similar time and space complexities.