DEV Community

Cover image for Maximum Number of Words Found in Sentences
Yajindra Gautam
Yajindra Gautam

Posted on

Maximum Number of Words Found in Sentences

Maximum Number of Words Found in Sentences

A sentence is a list of words that are separated by a single space with no leading or trailing spaces.

You are given an array of strings sentences, where each sentences[i] represents a single sentence.

Return the maximum number of words that appear in a single sentence.

Example 1:


Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
Output: 6
Explanation: 
- The first sentence, "alice and bob love leetcode", has 5 words in total.
- The second sentence, "i think so too", has 4 words in total.
- The third sentence, "this is great thanks very much", has 6 words in total.
Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.

Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: sentences = ["please wait", "continue to fight", "continue to win"]
Output: 3
Explanation: It is possible that multiple sentences contain the same number of words. 
In this example, the second and third sentences (underlined) have the same number of words.

Enter fullscreen mode Exit fullscreen mode

Constraints:

  • 1 <= sentences.length <= 100.
  • 1 <= sentences[i].length <= 100
  • sentences[i] consists only of lowercase English letters and ' ' only.
  • sentences[i] does not have leading or trailing spaces.
  • All the words in sentences[i] are separated by a single space.

The approach I have used here is the simplest, first I splice() it user forEach loop to fetch a sentence and spit it to count the words in it. Then compare it with temp.
If sentence length is greater than the temp then I keep swiping the value until the maximum word is found.

The code is given below :

var mostWordsFound = function(sentences) {
     const splitedArray = sentences.splice(',');
    let temp = 0;
    splitedArray.forEach((sentance, i) => {
        if(sentance.split(' ').length > temp){
              temp = sentance.split(' ').length;
        }
    });

    return temp;
};
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)

Space Complexity: O(1)

Following is my code runtime and memory usage.

Image description

Runtime And Memory Usage

Hope this post is helpful. I share my knowledge and teach people about programming and we have more than 12k @codewithyahi Instagram family.

Since you enjoyed reading my blog, why not buy me a coffee and support my work here!! https://www.buymeacoffee.com/yajindra☕

Top comments (0)