Maximum Number of Words Found in Sentences (LeetCode 2114): Solution and Explanation

Easy
Array
String

Each string in the array is a sentence of words separated by single spaces. Return the largest number of words in any one sentence.

Intuition

Because words are separated by exactly one space and nothing sits at either end, every space sits between two words. A sentence with k spaces therefore has k + 1 words.

That turns word counting into character counting, with no need to build a list of words.

The answer is the maximum of those counts, which a single running variable tracks as you go.

Approach: Count spaces, keep the maximum

  1. Set best = 0.
  2. For each sentence, count its spaces and add 1 to get the number of words.
  3. Update best = max(best, words).
  4. Return best.

Step-by-step example

sentences = ["alice and bob love leetcode","i think so too","this is great thanks very much"]
  1. Sentence 0 has 4 spaces, so 5 words. best = 5.
  2. Sentence 1 has 3 spaces, so 4 words. 4 is not more than 5, best stays 5.
  3. Sentence 2 has 5 spaces, so 6 words. best = 6.
  4. Return 6.

Code: Python, Java, C++

1class Solution:
2    def mostWordsFound(self, sentences: List[str]) -> int:
3        best = 0
4        for sentence in sentences:
5            words = sentence.count(' ') + 1
6            best = max(best, words)
7        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(L)

L is the total number of characters across all sentences; each is looked at once.

Space

O(1)

Counting spaces needs no extra storage. Splitting into words would use O(length) per sentence.

Other approaches

Split each sentence (time O(L), space O(max sentence length))

Split on spaces and take the length of the resulting list. Clear and short, but it allocates a list of words for every sentence.

Count word starts (time O(L), space O(1))

Count positions where a letter follows a space or starts the string. This version also works when spaces can repeat or appear at the ends.

Common mistakes

  • Forgetting the + 1: the number of spaces is one less than the number of words.
  • Initializing best to the first sentence's count and then skipping it in the loop, or reading sentences[0] without checking the list.
  • Using a split that collapses whitespace in one language and not in another when porting the solution. With single spaces both agree, but it matters if the input rules change.

Frequently asked questions

Why does counting spaces work?

Each space separates two adjacent words, and there are no spaces at the start or end. So n words always come with exactly n - 1 spaces.

Is splitting slower than counting?

Both are linear in the length of the text. Splitting allocates strings, so counting is a little lighter, but either is fine for these limits.

What if two sentences tie?

The problem only asks for the count, so ties do not matter: the maximum is the same either way.