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;
}

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;
}

Common mistakes

  • PHP str_word_count only counts letters, so "PHP 8" gives 1.