Top K Frequent Words

Medium

Topics
ArrayStringHash TableHeapSortingCounting

Given an array of strings words and an integer k, return the k most frequent words.

The result is sorted by frequency, highest first. Words that occur the same number of times are ordered alphabetically, which makes the answer unique.

Example 1

rankedi ×2love ×2coding ×1leetcode ×1
answerilove
in the answerranked below the cut
These 6 words hold 4 distinct ones, shown with their counts and already in answer order, and k = 2 takes the first 2. The ordering runs by count from the highest down. Where counts are equal the alphabet settles it, which is why i precedes love — both occur 2 times and nothing else could separate them.
The answer is the words in order, without their counts.
Input:  words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: Both occur twice, and "i" sorts before "love".

Example 2

rankedthe ×4is ×3sunny ×2day ×1
answertheissunnyday
in the answer
No two words here share a count, so the alphabetical tie-break never comes into play on this input.
Input:  words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: Counts are 4, 3, 2, 1, so no tie-break is needed.

Example 3

rankeda ×1b ×1c ×1
answerabc
in the answer
Input:  words = ["a","b","c"], k = 3
Output: ["a","b","c"]
Explanation: Every word occurs once, so the whole answer is decided alphabetically.

Constraints

  • 1 <= words.length <= 500
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters
  • 1 <= k <= number of distinct words
Editorial — intuition, approach, complexity and pitfalls

Intuition

Counting is the easy half. The half that decides whether an answer is accepted is the ordering, because the two keys run in opposite directions: count descending, but word ascending. Sorting by one and then reversing gets the second key backwards.

The clean way to say it is a single comparison that returns "a before b" when a has the larger count, and falls through to the plain string comparison when the counts are equal. Expressed as a sort key in Python that is (-count, word), which gets both directions right at once.

If k is much smaller than the number of distinct words, a full sort does more work than needed and a size-k container suffices. The subtlety is that such a container has to discard the worst element, so its comparison is the inverse of the one above — and inverting a two-key comparison means flipping both keys, not just the count.

That inversion is where this problem actually bites. A container ordered by "smallest count first" will, among equal counts, want the alphabetically largest word at the top so it can throw that one away.

Approach

  1. Count occurrences of each word.
  2. Sort the distinct words by count descending, then by the word ascending, and take the first k.
  3. For the size-limited variant: keep a container of at most k entries ordered worst-first, meaning smallest count, and among equal counts the alphabetically largest word. Push each distinct word, and whenever the size exceeds k, drop the top.
  4. Reverse what remains to get best-first order, since the container held them worst-first.

Walkthrough

words = ["the","day","is","sunny","the","the","the","sunny","is","is"]
k = 4

counts
   the   4
   is    3
   sunny 2
   day   1

sort key (-count, word)
   the    (-4, "the")
   is     (-3, "is")
   sunny  (-2, "sunny")
   day    (-1, "day")

answer: the is sunny day

now a case where the tie-break matters
words = ["i","love","leetcode","i","love","coding"], k = 2
   i        2
   love     2
   coding   1
   leetcode 1

keys: i (-2,"i"), love (-2,"love")
   equal counts, so "i" < "love" decides it

answer: i love        NOT love i

Complexity

  • Time — O(n + d log d): counting is linear in the input; the sort is over the d distinct words.
  • Space — O(d): one entry per distinct word.

Common Pitfalls

  • Sorting by count ascending and reversing. That reverses the alphabetical key too, so tied words come out backwards.
  • Comparing word lengths instead of the words themselves. The tie-break is dictionary order, so "zoo" comes after "apple".
  • Using a size-k container with the same comparison as the final sort. It has to be inverted, and inverting means flipping both keys.
  • Returning counts alongside the words. The answer is the words only.
  • Assuming k can exceed the number of distinct words. It cannot, so no padding case is needed.

Full Solution — all languages

class Solution:
    def topKFrequent(self, words, k):
        counts = {}
        for w in words:
            counts[w] = counts.get(w, 0) + 1

        # Count descending, word ascending. Negating the count lets one
        # ascending sort express both directions at once.
        ordered = sorted(counts, key=lambda w: (-counts[w], w))
        return ordered[:k]
SensAI
Beta
Tap the mic to stop voice mode