2114. Maximum Number of Words Found in Sentences
Problem Description
You are given an array of strings called sentences
, where each element represents a single sentence. A sentence is defined as a list of words separated by single spaces, with no leading or trailing spaces.
Your task is to find the maximum number of words that appear in any single sentence from the given array.
For example, if you have sentences like:
- "alice and bob love leetcode" (5 words)
- "i think so too" (4 words)
- "this is great thanks very much" (6 words)
The answer would be 6
since the third sentence contains the most words.
The solution cleverly counts the number of spaces in each sentence and adds 1
to get the word count (since the number of words equals the number of spaces plus one). It then returns the maximum value found across all sentences.
Intuition
The key observation is that in a properly formatted sentence (no leading or trailing spaces, single spaces between words), there's a direct relationship between the number of spaces and the number of words.
If we think about how words are separated in a sentence:
- 1 word has 0 spaces: "hello"
- 2 words have 1 space: "hello world"
- 3 words have 2 spaces: "hello world everyone"
- n words have n-1 spaces
This pattern reveals that number of words = number of spaces + 1
.
Instead of splitting each sentence into an array of words and counting them (which would require more memory and processing), we can simply count the spaces. This is more efficient because:
- Counting characters is a simple linear scan through the string
- We don't need to create any intermediate data structures
- The built-in
count()
method is optimized for this operation
So the approach becomes straightforward: for each sentence, count the spaces, add 1 to get the word count, and keep track of the maximum across all sentences. This gives us the answer in a single pass through the data with minimal overhead.
Solution Approach
The solution uses a simple space counting technique to determine the number of words in each sentence.
Implementation Steps:
-
Iterate through all sentences: We need to examine each sentence in the
sentences
array to find which one has the most words. -
Count spaces in each sentence: For each sentence
s
, we uses.count(' ')
to count the number of space characters. This built-in string method efficiently counts all occurrences of the space character. -
Calculate word count: Since words are separated by spaces, the number of words equals the number of spaces plus 1. For example:
- "hello world" has 1 space → 2 words
- "a b c d" has 3 spaces → 4 words
-
Find the maximum: We use Python's
max()
function with a generator expression(s.count(' ') for s in sentences)
to find the sentence with the most spaces. The generator expression avoids creating an intermediate list, making it memory-efficient. -
Return the result: Add 1 to the maximum space count to get the maximum word count.
Complete Solution:
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return 1 + max(s.count(' ') for s in sentences)
Time Complexity: O(n × m)
where n
is the number of sentences and m
is the average length of each sentence, as we need to scan through each character of each sentence.
Space Complexity: O(1)
as we only use a constant amount of extra space regardless of input size.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a small example with the input: sentences = ["hello world", "leetcode", "the quick brown fox"]
Step 1: Process the first sentence "hello world"
- Count spaces: There is 1 space between "hello" and "world"
- Word count: 1 space + 1 = 2 words
- Current maximum: 2
Step 2: Process the second sentence "leetcode"
- Count spaces: There are 0 spaces (single word)
- Word count: 0 spaces + 1 = 1 word
- Current maximum: remains 2 (since 1 < 2)
Step 3: Process the third sentence "the quick brown fox"
- Count spaces: There are 3 spaces (between "the"-"quick", "quick"-"brown", "brown"-"fox")
- Word count: 3 spaces + 1 = 4 words
- Current maximum: updates to 4 (since 4 > 2)
Step 4: Return the result
- The maximum word count found is 4
Using the one-liner solution: 1 + max(s.count(' ') for s in sentences)
- The generator produces: 1, 0, 3 (space counts for each sentence)
max(1, 0, 3)
= 3- Final result: 1 + 3 = 4
Therefore, the function returns 4, which is the maximum number of words in any single sentence.
Solution Implementation
1class Solution:
2 def mostWordsFound(self, sentences: List[str]) -> int:
3 """
4 Find the maximum number of words in any sentence.
5
6 Args:
7 sentences: A list of strings where each string is a sentence.
8
9 Returns:
10 The maximum number of words found in any single sentence.
11 """
12 # Count spaces in each sentence and add 1 to get word count
13 # (number of words = number of spaces + 1)
14 max_word_count = 1 + max(sentence.count(' ') for sentence in sentences)
15
16 return max_word_count
17
1class Solution {
2 public int mostWordsFound(String[] sentences) {
3 int maxWordCount = 0;
4
5 // Iterate through each sentence in the array
6 for (String sentence : sentences) {
7 // Initialize word count to 1 (minimum one word if sentence is not empty)
8 int wordCount = 1;
9
10 // Count spaces to determine number of words
11 // Number of words = Number of spaces + 1
12 for (int i = 0; i < sentence.length(); i++) {
13 if (sentence.charAt(i) == ' ') {
14 wordCount++;
15 }
16 }
17
18 // Update maximum word count if current sentence has more words
19 maxWordCount = Math.max(maxWordCount, wordCount);
20 }
21
22 return maxWordCount;
23 }
24}
25
1class Solution {
2public:
3 int mostWordsFound(vector<string>& sentences) {
4 int maxWordCount = 0;
5
6 // Iterate through each sentence in the vector
7 for (const auto& sentence : sentences) {
8 // Count words by counting spaces and adding 1
9 // (number of words = number of spaces + 1)
10 int wordCount = 1 + count(sentence.begin(), sentence.end(), ' ');
11
12 // Update the maximum word count found so far
13 maxWordCount = max(maxWordCount, wordCount);
14 }
15
16 return maxWordCount;
17 }
18};
19
1/**
2 * Finds the maximum number of words in any sentence from the array
3 * @param sentences - Array of sentences to analyze
4 * @returns The maximum word count found among all sentences
5 */
6function mostWordsFound(sentences: string[]): number {
7 // Iterate through all sentences and find the maximum word count
8 return sentences.reduce(
9 (maxWordCount, currentSentence) =>
10 Math.max(
11 maxWordCount,
12 // Count words by counting spaces and adding 1
13 // Convert string to array to iterate through characters
14 [...currentSentence].reduce(
15 (wordCount, character) =>
16 wordCount + (character === ' ' ? 1 : 0),
17 1 // Start with 1 word (spaces + 1 = total words)
18 ),
19 ),
20 0 // Initial maximum value
21 );
22}
23
Time and Space Complexity
The time complexity is O(L)
, where L
is the total length of all strings in the array sentences
. This is because the algorithm needs to traverse through each character in every sentence to count the spaces. The count(' ')
method for each string takes time proportional to the length of that string, and we apply this operation to all sentences in the list.
The space complexity is O(1)
. The algorithm only uses a constant amount of extra space regardless of the input size. The generator expression (s.count(' ') for s in sentences)
doesn't create a list but instead generates values one at a time, and the max()
function only needs to keep track of the maximum value seen so far, requiring constant space.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Assuming Empty Input Array
The solution will fail if the sentences
array is empty because max()
cannot operate on an empty sequence.
Example of failure:
sentences = [] # This will raise: ValueError: max() arg is an empty sequence
Solution:
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
if not sentences: # Handle empty array
return 0
return 1 + max(sentence.count(' ') for sentence in sentences)
2. Multiple Consecutive Spaces
The current solution assumes sentences are well-formatted with single spaces between words. If there are multiple consecutive spaces, the word count will be incorrect.
Example of incorrect behavior:
sentences = ["hello world"] # Two spaces between words # Current solution returns 3 (counting 2 spaces + 1) # But there are actually only 2 words
Solution:
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
max_words = 0
for sentence in sentences:
# Split handles multiple spaces correctly
word_count = len(sentence.split())
max_words = max(max_words, word_count)
return max_words
3. Leading or Trailing Spaces
Although the problem states there are no leading or trailing spaces, if the input violates this assumption, the count will be off.
Example of incorrect behavior:
sentences = [" hello world "] # Leading and trailing spaces # Current solution counts 2 spaces, returns 3 # But there are actually only 2 words
Solution:
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max(len(sentence.strip().split()) for sentence in sentences) if sentences else 0
4. Performance Consideration for Very Long Sentences
While the space-counting approach is efficient, using split()
might be more readable and handles edge cases better, with negligible performance difference for typical inputs.
Alternative robust solution:
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
# More robust: handles multiple spaces, leading/trailing spaces
return max((len(s.split()) for s in sentences), default=0)
Given a sorted array of integers and an integer called target, find the element that
equals to the target and return its index. Select the correct code that fills the
___
in the given code snippet.
1def binary_search(arr, target):
2 left, right = 0, len(arr) - 1
3 while left ___ right:
4 mid = (left + right) // 2
5 if arr[mid] == target:
6 return mid
7 if arr[mid] < target:
8 ___ = mid + 1
9 else:
10 ___ = mid - 1
11 return -1
12
1public static int binarySearch(int[] arr, int target) {
2 int left = 0;
3 int right = arr.length - 1;
4
5 while (left ___ right) {
6 int mid = left + (right - left) / 2;
7 if (arr[mid] == target) return mid;
8 if (arr[mid] < target) {
9 ___ = mid + 1;
10 } else {
11 ___ = mid - 1;
12 }
13 }
14 return -1;
15}
16
1function binarySearch(arr, target) {
2 let left = 0;
3 let right = arr.length - 1;
4
5 while (left ___ right) {
6 let mid = left + Math.trunc((right - left) / 2);
7 if (arr[mid] == target) return mid;
8 if (arr[mid] < target) {
9 ___ = mid + 1;
10 } else {
11 ___ = mid - 1;
12 }
13 }
14 return -1;
15}
16
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!