progress

~/problems / Arrays & hashing / Python toolkit

Most common words with Counter

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write top_words(words: list[str], k: int) -> list[tuple[str, int]] that returns the k most frequent words as (word, count) pairs, using collections.Counter.

  • The most frequent word comes first.
  • Words with the same count keep the order of their first appearance in words.
  • If there are fewer than k different words, return all of them. k == 0 or an empty list gives [].
top_words(["red", "blue", "red", "green", "blue", "red"], 2)   # [("red", 3), ("blue", 2)]
top_words(["b", "a", "a", "b", "c"], 2)                       # [("b", 2), ("a", 2)]   (b appeared first)
top_words(["x"], 5)                                           # [("x", 1)]
  • 0 <= len(words) <= 10^5 and 0 <= k <= 10^5. Words are compared exactly: "Red" and "red" are different words.
  • Don't modify words.
Show hint

Counter(words) counts everything in one pass, and its most_common(k) method already returns the pairs in the order asked for, ties included.

Topic: Python toolkit. Counter, deque, heapq, bisect, itertools: the standard library to know cold, and its traps.

0:00
Ctrl ' run · Ctrl ↵ submit
esc