Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style 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(["the", "day", "is", "sunny", "the", "the", "sunny", "is", "is"], 4))
What is printed?
  1. A. ['the', 'is', 'sunny', 'day']
  2. B. ['is', 'the', 'day', 'sunny']
  3. C. ['the', 'is', 'sunny']
  4. D. ['is', 'the', 'sunny', 'day']

Correct answer: D. ['is', 'the', 'sunny', 'day']

Sort by (−count, word): 'is' and 'the' both appear 3 times, so alphabetical order puts 'is' first; then 'sunny' (2) and 'day' (1). Sorting by count alone keeps insertion order for ties ('the' first). O(m log m) for m distinct words; a size-k heap gives O(m log k).

More Coding Interview Problems questions

Exams that ask this topic