Code Logo

Maximum Words in Sentence

Published at25 Jul 2026
Medium 1 views
Like0

Given an array of strings where each string represents a sentence containing words separated by single spaces, find the maximum number of words in any single sentence. Return the highest word count among all sentences.

For example, the sentences ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] have word counts 5, 4, and 6 respectively. The maximum is 6. An empty array returns 0.

Counting words in sentences is a fundamental text processing task. Word counts are used in readability analysis (Flesch-Kincaid grade level), document similarity (TF-IDF), text summarization, and search relevance scoring. The word count of a sentence is typically computed by counting the spaces plus one, or by splitting on spaces and taking the array length.

The simplest approach iterates through each sentence, splits it by spaces into words, counts them, and tracks the maximum count seen so far. This runs in O(N) time where N is the total number of characters across all sentences.

Edge cases include an empty array (return 0), a single empty string (return 0), sentences with one word (word count is 1), and all sentences having the same word count (return that count).

Example Input & Output

Example 1
Input
"The quick brown fox"
Output
4
Explanation

4 words in the sentence

Example 2
Input
"Hello World"
Output
2
Explanation

2 words

Example 3
Input
"a"
Output
1
Explanation

Single word

Example 4
Input
" spaced out "
Output
2
Explanation

Two words with extra spaces

Example 5
Input
""
Output
0
Explanation

Empty string

Algorithm Flow

Recommendation Algorithm Flow for Maximum Words in Sentence

Solution Approach

Iterate through sentences, count words in each, and track the maximum.

function solution(sentences) {
  var max = 0;
  for (var i = 0; i < sentences.length; i++) {
    var count = sentences[i].split(' ').length;
    if (count > max) max = count;
  }
  return max;
}

Initialize max to 0. For each sentence, split by spaces to get an array of words, take its length to get the word count. If the current count exceeds max, update max. After processing all sentences, return max.

An alternative approach counts spaces instead of splitting: the number of words equals the number of spaces plus one (for non-empty strings). This avoids creating intermediate arrays.

Time complexity is O(N) where N is total characters. Space complexity is O(1) aside from the split arrays.

Best Answers

java
class Solution {
    public int solution(String s) {
        s=s.trim();if(s.isEmpty())return 0;return s.split("\\s+").length;
    }
}