Code Logo

Maximum Words in Sentence

Published at25 Jul 2026
Medium 0 views
Like0

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
Recommendation Algorithm Flow for Maximum Words in Sentence

Solution Approach

function solution(s) {
  s = s.trim();
  if (s.length === 0) return 0;
  return s.split(/\s+/).length;
}

Best Answers

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