MediumArrayHash TableStringTrieSortingHeap (Priority Queue)Bucket SortCounting

Top K Frequent Words

LeetCode
1 approach, code in all languages

You are given a list of words and an integer k. Return the k words that appear most frequently.

Order the answer by frequency from highest to lowest. When two words occur the same number of times, place the lexicographically smaller word first.

Example 1

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

Output: ["i","love"]

"i" and "love" both appear twice; the others appear once, so the two most frequent words are returned.

Example 2

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

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

Counts are the:4, is:3, sunny:2, day:1, so they are ordered by decreasing frequency.

Constraints

  • 1 <= words.length <= 500
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters
  • k is in the range [1, the number of unique words]
  • Words with the same frequency are ordered lexicographically
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now