Problem Statement
Count the number of words in a sentence.
Example Inputs
- Input:
"The quick brown fox"
- Input:
"JavaScript is fun"
- Input:
"Count the number of words"
- Input:
"OpenAI creates amazing AI"
JavaScript Method - Using Only String Methods
Approach
To count the number of words in a sentence, we can split the sentence into an array of words using spaces as delimiters and then count the length of the resulting array.
Steps
- Use
.trim()
to remove any leading or trailing spaces.
- Use
.split(' ')
to split the sentence by spaces into an array of words.
- Filter out any empty strings in the array to handle extra spaces.
- Return the length of the filtered array as the word count.
Time & Space Complexity
- Time Complexity: O(n), where n is the length of the string, as we traverse each character once.
- Space Complexity: O(m), where m is the number of words in the sentence, due to storing words in an array.
Code Snippet
Dry Run
Example input: "The quick brown fox"
- Step 1:
sentence.trim()
→ "The quick brown fox"
- Step 2:
"The quick brown fox".split(' ')
→ ['The', 'quick', 'brown', 'fox']
- Step 3: Filter out empty strings (none in this case)
- Step 4:
['The', 'quick', 'brown', 'fox'].length
→ 4
Final output: 4
Alternative Approach - Using Loop and Conditionals
Approach
We can manually count words by looping through each character and counting transitions from spaces to non-space characters.
Steps
- Initialize a
count
variable to 0.
- Use a loop to iterate through each character in the sentence.
- If a character is not a space and is preceded by a space or is at the start, increment the
count
.
- Return
count
as the total number of words.
Time & Space Complexity
- Time Complexity: O(n), as we iterate through each character once.
- Space Complexity: O(1), since only a counter is used.
Code Snippet
Dry Run
Example input: "The quick brown fox"
- Initialize:
count = 0
, inWord = false
- Loop through
"The quick brown fox"
:
T
→ inWord = true
, count = 1
- Continue to
h
, e
(still inWord)
- Space after
The
→ inWord = false
q
→ new word, inWord = true
, count = 2
- Continue for each word in a similar manner
- Final output:
4
Complexity Analysis
JavaScript Method (Using String Methods)
- Time Complexity: O(n)
- Space Complexity: O(m)
Alternative Approach (Using Loop and Conditionals)
- Time Complexity: O(n)
- Space Complexity: O(1)
Conclusion
Counting words in a sentence can be achieved by splitting the sentence into an array or by using a manual counting approach. The loop-based approach is optimal in terms of space, while the split method is simpler to implement.