KatInterview

Top-K Most Frequent Words by Score

Heaps, Sorting & SearchAuto-graded · 17 test cases

Last updated

Tests ability to rank words by a weighted frequency-length score, applying top-k selection with a precise tie-breaking rule.

Word Ranking by Score

You are building a search-relevance tool that scores words from a document and returns the most important ones.

Given a list of words and an integer k, compute a score for each unique word and return the top k words by score.

Scoring rule

For each unique word w, its score is:

score(w) = frequency(w) * len(w)

where frequency(w) is the number of times w appears in the input list (case-sensitive).

Tie-breaking

If two words have the same score, the word that comes earlier in lexicographic (alphabetical) order ranks higher.

Return a list of exactly k words in descending score order (highest score first), with ties broken as described.

Constraints

  • 1 <= len(words) <= 2000
  • 1 <= k <= number of unique words
  • Each word consists of lowercase English letters only.
  • 1 <= len(w) <= 50 for every word w.
  • The answer is always unique given the tie-break rule.

Examples

Example 1

Input: top_k_words_by_score(['the', 'cat', 'sat', 'on', 'the', 'mat', 'the', 'cat'], 3)

Output: ['the', 'cat', 'mat']

Example 2

Input: top_k_words_by_score(['ab', 'ab', 'ab', 'cd', 'cd', 'efg'], 2)

Output: ['ab', 'cd']

Example 3

Input: top_k_words_by_score(['hello', 'world', 'hello', 'world', 'hello'], 1)

Output: ['hello']

Hints

Hint 1

Count the frequency of each word first, then compute score = frequency × word length for each unique word.

Hint 2

Use a sort key of (-score, word) so that higher scores come first and lexicographically smaller words break ties.

Hint 3

After sorting, simply slice the first k elements of the sorted list.