Most Common Word
Medium · rating 1200 · hashing, strings
Read a line of lowercase words separated by single spaces. Print the word that appears most often. If several words tie, print the lexicographically smallest.
Editorial
Most Common Word finds the highest-frequency word, breaking ties alphabetically. Count words with a hash map, then choose the best — the smallest word on a tie.
from collections import Counter
counts = Counter(words)
best = min(counts, key=lambda w: (-counts[w], w))
print(best)Complexity
Time: O(n). Space: O(k) for k distinct words.