Count Words
Easy About 8 min Free, no account needed
Count words by spotting boundaries, not by splitting.
The brief
Given a string text, return the number of words, maximal runs of
non-space characters (separators are plain spaces; leading, trailing and
repeated spaces are all possible).
Split with RemoveEmptyEntries allocates every word just to count them. The
hidden test has 15,000 words under a 32 KB allocation budget. Count the words
in one pass with zero allocations.
Starter code
using System;
public class Solution
{
// TODO: return the number of maximal runs of non-space characters.
public int CountWords(string text)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
Related guides
What it practices
- String processing
- Parse, scan and match text character by character with correct edge cases.
- Allocation-free code
- Avoid per-item strings and copies with spans, indexes and arithmetic in hot loops.
Related katas
- Parse and Sum Integers Easy Free Sum space-separated integers (negatives included) allocation-free.
- Count Substring Occurrences Medium Free Count overlapping occurrences by comparing characters, not slicing strings.
- Hex Checksum Medium Free Sum the bytes of a hex string with nibble arithmetic, not substrings.
- Most Common Word Length Medium Free Which word length appears most often? Count lengths, not words.