Tally Tokens and Report the Three Most Common
Arrays & HashingAuto-graded · 18 test casesLast updated
Count occurrences of each string in a list with a hash map, then rank by count with an alphabetical tie-break to extract the top three entries.
You are given a list of strings, where each element is already a single token. Do not split, trim, strip punctuation, or change the case of any element. Comparison is exact, so "Tea" and "tea" are different tokens, and the empty string "" is a valid token.
Write a function that returns a dictionary with two keys:
"frequencies": a dictionary mapping every distinct token in the input to the number of times it occurs."top_three": a list of at most three[token, count]pairs (each pair is a two-element list, not a tuple) describing the most common tokens.
Ranking rules
- Order the pairs by
countfrom highest to lowest. - If two tokens have the same count, the one that comes first in ordinary string (lexicographic) order is listed first.
- If there are fewer than three distinct tokens, include them all. Do not pad the list.
- If the input is empty,
"frequencies"is{}and"top_three"is[].
The function should only return the data and should not print anything.
Constraints
0 <= len(words) <= 10^5- Each element of
wordsis a string (possibly empty). - Tokens are compared exactly as given, with case sensitivity.
- The result must contain exactly the two keys described above.
Examples
Example 1
Input: count_tokens_top_three(['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'pear'])
Output: {'frequencies': {'apple': 3, 'banana': 2, 'orange': 1, 'pear': 1}, 'top_three': [['apple', 3], ['banana', 2], ['orange', 1]]}
Example 2
Input: count_tokens_top_three(['the', 'quick', 'brown', 'fox', 'the', 'fox', 'the'])
Output: {'frequencies': {'the': 3, 'quick': 1, 'brown': 1, 'fox': 2}, 'top_three': [['the', 3], ['fox', 2], ['brown', 1]]}
Hints
Hint 1
Make one pass over the list and keep a dictionary from token to its running count; dict.get(token, 0) + 1 avoids a separate membership check.
Hint 2
Sort the (token, count) items with a composite key that puts larger counts first while keeping tokens in ascending order for ties.
Hint 3
Negate the count inside the sort key instead of using reverse=True, which would also reverse the alphabetical tie-break. Slice the first three results so fewer than three entries is handled safely.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two phases.
-
Count. Walk through the list once. For each token, set
frequencies[token] = frequencies.get(token, 0) + 1. The default of 0 means a token is added the first time it is seen, so no separate "is it present?" branch is needed. -
Rank. Sort the dictionary's
(token, count)items using the key(-count, token). Negating the count makes higher counts come first in an ascending sort, and the token as the second component orders equal counts alphabetically. Slice the first three entries and convert each tuple into a[token, count]list.
Why it is correct
- Every element of the input is visited exactly once and adds exactly 1 to its own entry, so each final value is that token's true number of occurrences. Only tokens that appear get keys.
- Python compares tuples lexicographically. If one item has a larger count, its negated count is smaller and it sorts first. If counts are equal, the comparison moves to the token, so the alphabetically smaller token comes first. This is exactly the required ordering.
- Slicing with
[:3]returns the three best-ranked items, or all of them when fewer than three distinct tokens exist, and an empty list for empty input. No padding or indexing errors occur.
Using reverse=True with a count-only key would be wrong, since it leaves ties in insertion order (or reverses the alphabetical order if the token is included).
Complexity
Let n = len(words) and k be the number of distinct tokens.
- Time: O(n) for counting plus O(k log k) for sorting, so O(n + k log k).
- Space: O(k) for the dictionary and the sorted list.
A heap-based selection such as heapq.nsmallest(3, items, key=...) can reduce the ranking step to O(k log 3), but the plain sort is simpler and fast enough here.
Reference solution
from typing import Dict, List
def count_tokens_top_three(words: List[str]) -> Dict[str, object]:
# Phase 1: count occurrences with a plain dictionary.
frequencies = {}
for word in words:
frequencies[word] = frequencies.get(word, 0) + 1
# Phase 2: rank by count descending, then token ascending for ties.
ranked = sorted(frequencies.items(), key=lambda item: (-item[1], item[0]))[:3]
return {
"frequencies": frequencies,
"top_three": [[word, count] for word, count in ranked],
}