KatInterview

Top-K Most Frequent Words With Tie-Breaking

Heaps, Sorting & SearchAuto-graded · 17 test cases
EasyAuto-gradedHeaps, Sorting & Searchheapsortinghash map

Last updated

Tests ability to retrieve the k most frequent words from a list, using lexicographic order as a tie-breaker, via a heap or sort-based approach.

Top-K Most Frequent Words

You are building a tag-analytics dashboard. Given a list of word tags and a positive integer k, return the k most frequently occurring words, ordered by:

  1. Descending frequency (most frequent first).
  2. Ascending lexicographic order as a tie-breaker (so among words with the same count, alphabetically earlier words come first).

Return exactly k words. It is guaranteed that there are at least k distinct words in the input.

Constraints

  • 1 <= len(words) <= 2000
  • 1 <= k <= number of distinct words in words
  • Each word consists of lowercase English letters only (a–z).
  • 1 <= len(word) <= 20 for each word in words.
  • If multiple words share the same frequency, the one that comes earlier in lexicographic (alphabetical) order ranks higher.

Examples

Example 1

Input: top_k_frequent_words(['tag', 'bug', 'tag', 'fix', 'bug', 'tag'], 2)

Output: ['tag', 'bug']

Example 2

Input: top_k_frequent_words(['alpha', 'beta', 'gamma', 'alpha', 'beta', 'alpha'], 2)

Output: ['alpha', 'beta']

Example 3

Input: top_k_frequent_words(['zen', 'art', 'zen', 'art', 'pop'], 3)

Output: ['art', 'zen', 'pop']

Hints

Hint 1

Count frequencies with a dictionary or collections.Counter, then decide how to rank each word.

Hint 2

A (frequency, word) tuple can be sorted: sort by frequency descending and word ascending — try negating the frequency to turn it into a single ascending sort key.

Hint 3

A min-heap of size k works too: push (-freq, word) tuples so the heap naturally evicts the least-preferred entry, keeping the top k.