Count the Words in a Sentence
Solve this ProblemEasy10 min
Topics
BasicsStrings
Companies
TCSInfosysWipro
Given a sentence
text made of letters and spaces, return how many words it contains. Words are separated by one or more spaces, and there may be spaces at the start or the end.
Counting words looks like "count the spaces and add one", but that breaks as soon as spaces are doubled or appear at the edges. The reliable idea is to count word boundariesWord BoundaryThe point where a word begins or ends — e.g. a letter that follows a space or the start of the text. — the places where a word begins. Splitting on spaces works too, as long as the empty pieces created by extra spaces are thrown away.
Test Case 1:
Input:text = "the quick brown fox"
Output:4
Explanation:Four groups of letters separated by spaces.
Test Case 2:
Input:text = " many spaces here"
Output:3
Explanation:Extra spaces at the start and between words do not create extra words.
Constraints
- ◆
1 ≤ text.length ≤ 1000 - ◆
text contains English letters and spaces only
Try the Dry Run
Approach & Solutions
Count Where Words StartGood
A word starts at a non-space character that is either the first character of the text or comes right after a space. Count those starting points. Runs of spaces anywhere — at the start, end or between words — never create a start, so they cannot inflate the count.
Time
O(n)Space
O(1)Java
class Solution {
public int countWords(String text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
boolean startsWord = text.charAt(i) != ' ' && (i == 0 || text.charAt(i - 1) == ' ');
if (startsWord) {
count++;
}
}
return count;
}
}Split on SpacesOptimal
Split the text into words and count them. Python's split() and C++'s >> operator skip runs of spaces automatically; Java trims first and splits on one-or-more spaces (" +"); JavaScript filters out the empty pieces; C uses strtok on a copy, which also skips repeated separators.
Time
O(n)Space
O(n)Java
class Solution {
public int countWords(String text) {
String trimmed = text.trim();
return trimmed.isEmpty() ? 0 : trimmed.split(" +").length;
}
}