Maximum Words in Sentence
Published at25 Jul 2026
Created by M Ichsanul Fadhil
Given a string s containing words separated by spaces, return the number of words in the string. Words are sequences of non-space characters. Leading, trailing, and multiple consecutive spaces should be handled correctly.
Trim the string, then split by spaces and count the non-empty elements. Alternatively, use string splitting with filtering to count words.
Time complexity is O(n) and space is O(n) for the array of words.
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
Best Answers
java
class Solution {
public int solution(String s) {
s=s.trim();if(s.isEmpty())return 0;return s.split("\\s+").length;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
