KatInterview

Tally Tokens and Report the Three Most Common

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashinghash-mapcountingsorting

Last 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 count from 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 words is 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.