EasyArrays & Strings

Maximum Number of Words Found in Sentences โ€” Solution

Problem

You have a list of sentences, where each sentence is a non-empty string of words separated by single spaces. Find the maximum number of words any single sentence contains.

  • Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
  • Output: 6
  • Explanation: The third sentence has 6 words โ€” the most of any sentence in the list.

Intuition

Words in a sentence are separated by spaces, so the number of words equals the number of spaces plus one. Scanning each sentence for spaces (or splitting on spaces) and tracking the running maximum is all that's needed โ€” no sorting, no lookup structures.

Solution โ€” Count Words Per Sentence

For each sentence, count the spaces and add one to get the word count. Track the maximum across all sentences.

  1. Initialize max_words to 0.
  2. For each sentence, count the number of space characters.
  3. Word count = space count + 1.
  4. Update max_words if this sentence has more words.
  5. Return max_words.
1def mostWordsFound(sentences: list[str]) -> int:
2    max_words = 0
3    for sentence in sentences:
4        word_count = sentence.count(' ') + 1  # spaces + 1 = words
5        max_words = max(max_words, word_count)
6    return max_words

Time: O(n ยท m) where n is the number of sentences and m is the average sentence length โ€” every character is visited once.

Space: O(1) โ€” only a few integer variables; no auxiliary data structures needed.

Complexity Summary

ApproachTimeSpaceWhen to use
Count spaces per sentenceO(n ยท m)O(1)Always โ€” there is no faster approach for this problem

Common Mistakes

  • Counting spaces instead of words โ€” the word count is spaces + 1, not spaces. A sentence like "hello world" has one space but two words.
  • Using split() with a space argument โ€” in Python, "hello world".split(' ') returns ['hello', '', 'world'], inflating the count when multiple consecutive spaces exist. Use split() with no argument or count spaces directly.
  • Initializing max_words to 1 assuming there's always at least one word โ€” while the problem guarantees this, starting at 0 is safer and equally correct; it doesn't require an assumption about the input.
  • Forgetting the + 1 โ€” a loop that breaks out early or a one-liner that only counts spaces without adding one is the single most common bug here.

Related Problems

Ready to practice? Try it on SkillFlow

Adaptive problems, AI follow-up interviews, and a skill score that shows exactly where you need to improve.

Practice This Problem โ†’