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.
- Initialize
max_wordsto 0. - For each sentence, count the number of space characters.
- Word count = space count + 1.
- Update
max_wordsif this sentence has more words. - 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_wordsTime: 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
| Approach | Time | Space | When to use |
|---|---|---|---|
| Count spaces per sentence | O(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, notspaces. 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. Usesplit()with no argument or count spaces directly. - Initializing
max_wordsto1assuming there's always at least one word โ while the problem guarantees this, starting at0is 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
reverse-stringโ basic in-place character manipulation on a stringfirst-unique-character-in-a-stringโ scanning a string character by character to aggregate informationis-subsequenceโ single-pass character matching across two stringsvalid-anagramโ frequency counting over string characterslongest-common-prefixโ comparing multiple strings character by character