Drill 1: Top K Frequent Words
Given a list of words and an integer k, return the
k most frequent words. Break ties lexicographically.
Hidden answer: invariant, tests, and Python solution
Invariant: after counting, frequency is the source of truth and
sorting only decides rank. Test ties, k = 0, one word,
and more requested items than unique words.
from collections import Counter
def top_k_frequent_words(words, k):
counts = Counter(words)
ranked = sorted(counts, key=lambda word: (-counts[word], word))
return ranked[:k]