InferenceAI

Enter at least two characters to search.

Start free

Top K Words

mediumHeaps25 min25 XP

Return the k most frequent words, sorted by frequency (highest first) and then alphabetically.

Examples

EXAMPLE WALKTHROUGHtie broken by alphabet

A guided view of the published example, not a trace of your code.

INPUT[["i","love","leetcode","i","love","coding"],2]
TASKtop_k_words()
EXPECTED OUTPUT["i","love"]

Start with the input values shown in this example.

Example 1 of 3

Input: words = ["i","love","leetcode","i","love","coding"], k = 2

Output: ["i","love"]

Explanation: tie broken by alphabet

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

Output: ["the","is","sunny","day"]

Explanation: four words

Input: words = ["a"], k = 1

Output: ["a"]

Explanation: single

Hint 1

Count with a Counter, then sort the distinct words by (-count, word).

Topics

DSAHeapsPython