Top K Frequent Words

Given an array of strings words and an integer k, return the k most frequent words. Sort the answer by frequency from highest to lowest, and sort words with the same frequency in lexicographical order.

30:00

Top K Frequent Words
medium
Free written solution
Topics
Companies

Given an array of strings words and an integer k, return the k most frequent words. Sort the answer by frequency from highest to lowest, and sort words with the same frequency in lexicographical order.

Example 1:
Input: {"words":["i","love","leetcode","i","love","coding"],"k":2}
Output: ["i","love"]
Constraints:
  • 1≤words.length≤5001 \leq \text{words.length} \leq 500

  • 1≤words[i].length≤101 \leq \text{words}[i].\text{length} \leq 10

  • words[i] consists of lowercase English letters.

  • kk is in the range [1,number of unique words][1, \text{number of unique words}]

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

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

"i" is new, so it enters the count map with 1.

words (1/6 counted) · k = 2

i
love
leetcode
i
love
coding

count map (1 distinct)

i1

heap: higher count on top, ties alphabetical (0 entries)

filled after counting

answer (0/2)

(pops land here)

Variables
VariableValue
wordi
count["i"]1
DepthFunction Call
Stack empty
0/14