Maximum Number of Words Found in Sentences — Easy Problem & Solution
Maximum Number of Words Found in Sentences: A sentence is a list of words separated by single spaces, with no leading or trailing spaces.
- Difficulty: Easy
- Topics: Arrays, Strings
- Asked at: TCS, Accenture, Capgemini
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A sentence is a list of words separated by single spaces, with no leading or trailing spaces.
Given an array sentences, return the maximum number of words that appear in any single sentence.
Example 1
Input: sentences = ["alice and bob love codekairo","i think so too","this is great thanks very much"]
Output: 6
Explanation: The last sentence has six words.
Example 2
Input: sentences = ["please wait","continue to fight","continue to win"]
Output: 3
Example 3
Input: sentences = ["solo"]
Output: 1
Constraints
1 <= sentences.length <= 1001 <= sentences[i].length <= 100Words are separated by single spaces with no leading or trailing space.
How to solve Maximum Number of Words Found in Sentences
The formatting guarantee turns counting words into counting separators: n single spaces split a sentence into exactly n + 1 words.
Approach
- For each sentence, count the space characters.
- The word count is that plus one.
- Keep the largest value seen.
Why it works
Because there are no leading, trailing or repeated spaces, every space sits strictly between two words, so the separators and the gaps between words are in bijection.
Complexity
- Time —
O(total characters) - Space —
O(1)
Pitfalls
- Splitting on whitespace in a language that produces an empty leading token would be off by one on padded input — the guarantee is what makes the shortcut safe.
- Starting the count at 0 rather than 1 undercounts every sentence.
Reference solution
Python
from typing import List
def mostWordsFound(sentences: List[str]) -> int:
return max(s.count(" ") + 1 for s in sentences)JavaScript
var mostWordsFound = function(sentences) {
var best = 0;
for (var j = 0; j < sentences.length; j++) {
var s = sentences[j], words = 1;
for (var i = 0; i < s.length; i++) {
if (s.charAt(i) === " ") words++;
}
if (words > best) best = words;
}
return best;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.