Find the bug · Easy
Fix the Word Counter
Easy Find the bug
wordCount(text) returns the number of words in text, where words are separated by any run of whitespace (spaces, tabs, newlines). Leading and trailing whitespace does not count, and an empty or blank string has 0 words.
The counter below is right for neatly typed sentences only. Find the bug and fix it.
Example 1
Input: text = "hello world" Output: 2
Example 2
Input: text = " hello world " Output: 2 Explanation: The buggy version returns 7.
The buggy code
function wordCount(text) {
return text.split(" ").length;
}
function wordCount(text: string): number {
return text.split(" ").length;
}
def word_count(text: str) -> int:
return len(text.split(" "))
<?php
function wordCount(string $text): int
{
return count(explode(' ', $text));
}
class Solution {
public int wordCount(String text) {
return text.split(" ").length;
}
}
Hints
Hint 1
What does splitting "a b" on a single space return?
Hint 2
And what does splitting an empty string return?
Find and fix the bug
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the bug and the fix
Time O(n) · Space O(n)
The bug: splitting on a single space " " produces an empty string between every pair of consecutive spaces, and at the start and end of the text. Splitting an empty string returns one element ([""]), so blank input counts as one word. Tabs and newlines are not separators at all.
The fix: split on runs of whitespace and ignore empty pieces: text.trim().split(/\s+/) with a special case for blank text in JavaScript and Java, len(text.split()) in Python (no argument means "any whitespace, drop empties"), preg_split('/\s+/', $text, -1, PREG_SPLIT_NO_EMPTY) in PHP.
Fixed version
function wordCount(text) {
const trimmed = text.trim();
return trimmed === "" ? 0 : trimmed.split(/\s+/).length;
}
function wordCount(text: string): number {
const trimmed = text.trim();
return trimmed === "" ? 0 : trimmed.split(/\s+/).length;
}
def word_count(text: str) -> int:
return len(text.split()) # no argument: split on any whitespace run, drop empty pieces
<?php
function wordCount(string $text): int
{
return count(preg_split('/\s+/', $text, -1, PREG_SPLIT_NO_EMPTY));
}
class Solution {
public int wordCount(String text) {
String trimmed = text.trim();
return trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
}
}
Common mistakes
- PHP
str_word_countonly counts letters, so"PHP 8"gives 1.
More Code Clinic: Find the Bug problems
- Fix the Binary Search · Easy
- Fix the Two Sum Hash Map · Easy
- Fix the Longest Substring Without Repeats · Medium
- Fix Merge Intervals · Medium
- Fix the Mutable Default Argument · Easy
- Fix the Substring Check · Easy