Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Return the k most frequent words, ties broken alphabetically.

Problem: Return the k most frequent words, ties broken alphabetically.
from collections import Counter
def topk(words, k):
    c = Counter(words)
    return sorted(c, key=lambda w: (-c[w], w))[:k]
print(topk(["sql", "api", "node", "api", "sql", "go", "node", "rust", "go"], 3))
What is printed?
  1. A. ['api', 'sql', 'node']
  2. B. ['api', 'go', 'node']
  3. C. ['sql', 'api', 'node']
  4. D. ['api', 'go', 'sql']

Correct answer: B. ['api', 'go', 'node']

api, sql, node and go each appear twice and rust once. Sorting by (−count, word) puts the tied words in alphabetical order: api, go, node, sql, so the top 3 are api, go, node. Taking the first-seen order instead gives sql, api, node.

More Coding Interview Problems questions

Exams that ask this topic