KatInterview

Count Distinct Words in a Sentence

StringsAuto-graded · 18 test cases
EasyAuto-gradedStringsstringstokenizingparsing

Last updated

Tests the ability to tokenize a raw sentence string into normalized word tokens and count how many distinct words appear exactly once.

Singleton Word Counter

You are given a sentence string s consisting of words separated by one or more spaces. Words may contain letters (a–z, A–Z) and apostrophes ('), and nothing else will appear inside a word token. The sentence may also contain punctuation characters (., ,, !, ?, ;, :) that are attached to words (e.g. "hello," or "world!") and must be stripped before comparison.

Your task is to tokenize the sentence, normalize each token to lowercase, strip any leading or trailing punctuation characters (., ,, !, ?, ;, :) from each token, and then return the number of distinct words that appear exactly once (case-insensitively) in the resulting list of tokens.

Tokens that become an empty string after stripping (e.g. a standalone punctuation character somehow present) should be ignored entirely.

Details

  • Splitting is done on whitespace (one or more spaces; no tabs or newlines will appear).
  • Only the six punctuation characters listed (., ,, !, ?, ;, :) need to be stripped — they will only ever appear at the start or end of a token, never in the middle (apostrophes are mid-word only).
  • After stripping and lowercasing, count word frequencies; return the count of words with frequency exactly 1.
  • If s is an empty string or contains only whitespace, return 0.

Constraints

  • 0 ≤ len(s) ≤ 2000
  • s contains only printable ASCII characters.
  • At most 400 whitespace-separated tokens.

Examples

Example 1

Input: count_singleton_words('The cat sat on the mat.')

Output: 4

Example 2

Input: count_singleton_words('Hello, world! Hello again.')

Output: 2

Example 3

Input: count_singleton_words('')

Output: 0

Hints

Hint 1

Split on whitespace first, then process each token individually.

Hint 2

Use str.strip() with an explicit set of punctuation characters to clean each token before lowercasing.

Hint 3

A frequency dictionary (or collections.Counter) lets you count occurrences and then filter for exactly-once words in one pass.