Count Distinct Words in a Sentence
StringsAuto-graded · 18 test casesLast 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
sis an empty string or contains only whitespace, return0.
Constraints
0 ≤ len(s) ≤ 2000scontains 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a straightforward tokenization and frequency-counting task.
Steps
- Split on whitespace using
str.split()(handles multiple consecutive spaces automatically, and returns an empty list for all-whitespace or empty input). - Clean each token: call
token.strip(PUNCT)wherePUNCT = '.!?,;:'to remove leading/trailing punctuation, then.lower()to normalize case. - Filter empty strings: after stripping, a token could theoretically become empty — skip those.
- Count frequencies with
collections.Counter. - Count singletons: return the number of entries in the counter whose value equals 1.
Correctness
- All six punctuation characters are stripped from both ends of every token before comparison, so
"Hello,"and"Hello!"both normalize to"hello". - Case normalization ensures
"Hello"and"hello"are treated as the same word. - Apostrophes are never stripped (they only appear mid-word per constraints), so
"don't"stays"don't". - Empty-string check after stripping ensures no garbage tokens pollute the counter.
str.split()with no argument already handles zero-length or all-whitespace input by returning[], giving a count of 0.
Complexity
- Time: O(n) where n =
len(s)— one pass to split and clean, one pass to count, one pass to filter. - Space: O(t) where t = number of tokens (at most 400), for the word list and counter.
from collections import Counter
def count_singleton_words(s: str) -> int:
PUNCT = '.!?,;:'
tokens = s.split()
words = []
for token in tokens:
word = token.strip(PUNCT).lower()
if word:
words.append(word)
freq = Counter(words)
return sum(1 for count in freq.values() if count == 1)