KatInterview

Define and Implement a Streaming Unicode Word Counter

StringsModel answer
MediumModel answerStringstokenizationunicodestreaming

Last updated

Specify precise tokenization rules for counting words in text, then build a Unicode-aware counter that works on huge streams, with tests and a regex versus scanner comparison.

You are asked to write a function that reports how many words a text document contains. "Word" is ambiguous, so part of the task is to pin the definition down yourself.

What to do

  1. Write down your tokenization rules before coding. Cover at least:
    • Contractions such as it's and it’s.
    • Hyphenated compounds such as state-of-the-art.
    • Numbers with separators such as 3.14 and 1,000.
    • Surrounding punctuation, quotes and Unicode apostrophes.
    • Runs of whitespace, tabs and newlines.
    • Text in several scripts, including languages written without spaces.
  2. Implement count_words following those rules.
  3. Support very large inputs. The same logic must work on a multi-gigabyte file or a network stream read in chunks, and a word that straddles two chunks must be counted once.
  4. Write unit tests for corner cases: empty input, whitespace only, punctuation only, mixed languages, combining accents, and chunk boundaries.
  5. Analyze time and space complexity.
  6. Compare a regex-based tokenizer with a hand-written character scanner, and say when you would choose each.

Expected output: the list of rules, working code, tests, the complexity analysis and a short trade-off discussion. Defend your choices, since the rules matter as much as the code.

Hints

Hint 1

Decide what counts as a word character first. Unicode general categories (letters, numbers, combining marks) are a better basis than ASCII ranges, and they handle accented and non-Latin text.

Hint 2

Treat apostrophes, hyphens and, between digits only, periods and commas as connectors. A connector joins two word characters only if a word character is on both sides. Hold it as pending until the next character arrives.

Hint 3

Model the counter as a small state machine (in a word or not, pending connector, last character was a digit) and increment the count exactly when a new word begins. Because the state is tiny, you can feed it chunks of any size, and a word split across chunks is still counted once.

Hint 4

For the regex comparison, think about what happens when a match straddles a chunk boundary, and how you would handle that with a regex versus with scanner state.