Order Distinct Letters-Only Tokens by Popularity
StringsAuto-graded · 20 test casesLast updated
Extract case-insensitive ASCII-letter tokens from text, count them, and list the distinct words by descending count with alphabetical tie-breaks.
Frequency-Ordered Word List
You are given a block of text. Pull out every word it contains, tally how often each distinct word shows up, and return the distinct words arranged from most frequent to least frequent.
What counts as a word
- A word is a maximal run of consecutive ASCII letters (
a-zorA-Z). - Every other character acts as a separator. This includes spaces, other whitespace, punctuation, digits, apostrophes, hyphens, and any non-ASCII character.
- For example,
"don't"yields the wordsdonandt, and"abc123def"yieldsabcanddef.
- For example,
- Words are compared without regard to case, so
Apple,APPLEandappleare all the same word. Report each word in lowercase.
Required output
Return a list of the distinct lowercase words, ordered by:
- Number of occurrences, highest first.
- For words with the same number of occurrences, ascending alphabetical (lexicographic) order.
Each distinct word appears exactly once in the result. If the text contains no words (including when it is empty), return an empty list.
Function
Implement rank_words_by_count(text), which takes the string text and returns a list of strings.
Constraints
textmay be empty and may contain letters, digits, whitespace, punctuation, and other characters.- Only the ASCII letters
a-zandA-Zform words; all else separates them. - The result must be fully deterministic, following the ordering rules above.
- Aim for a single pass over the text to tokenize, then sort only the distinct words (roughly O(N + K log K) for text length N and K distinct words).
Examples
Example 1
Input: rank_words_by_count('Hello world! Hello.')
Output: ['hello', 'world']
Example 2
Input: rank_words_by_count('Alpha, beta, alpha; beta, gamma.')
Output: ['alpha', 'beta', 'gamma']
Hints
Hint 1
Think about two stages: first gather a count for each lowercase word, then order the distinct words.
Hint 2
Be careful to split only on non-ASCII-letter characters; checking `str.isalpha()` would wrongly accept letters like 'e' with an accent.
Hint 3
Sort using a composite key: the negated count (so larger counts come first) paired with the word itself for alphabetical tie-breaks.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The work splits into two phases.
- Tokenize and count. Scan the text once and pull out each maximal run of ASCII letters using the pattern
[A-Za-z]+. Lowercase each run and increment its entry in a hash map (Counter). - Order the distinct words. Sort the keys of the map using the key
(-count, word). Negating the count puts higher frequencies first, and ties are resolved by ascending string comparison.
Why it is correct
- Tokenization: The regex is greedy, so every match extends to the end of a run of letters, giving exactly one maximal run per word. Since the character class lists only ASCII letters, digits, punctuation, whitespace and non-ASCII characters all act as separators, as required. Using the regex (rather than
isalpha()) avoids treating accented characters as letters. - Case-insensitivity: Lowercasing before counting merges all case variants into one key.
- Ordering: Python compares tuples element by element. A larger count produces a smaller negated count and therefore sorts earlier. Equal counts fall through to comparing the words. Distinct words are never equal, so the final order is unique.
- Empty input: No matches means an empty counter, and sorting it gives
[].
Complexity
Let N be the text length and K the number of distinct words.
- Time: O(N) to tokenize and count, plus O(K log K) comparisons to sort the distinct words (each comparison may cost up to the word length).
- Space: O(K) words stored in the map and result, in addition to their lengths. Tokens are produced lazily, so no list of all tokens is built.
Reference solution
import re
from collections import Counter
from typing import List
def rank_words_by_count(text: str) -> List[str]:
counts = Counter(m.group(0).lower() for m in re.finditer(r"[A-Za-z]+", text))
return sorted(counts, key=lambda word: (-counts[word], word))