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

Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.

Input & Output

Example 1 — Basic Case
$ Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
💡 Note: "i" and "love" both appear 2 times (highest frequency). Since they have same frequency, lexicographical order doesn't matter between them, but both beat "leetcode" and "coding" which appear only once.
Example 2 — Lexicographical Tiebreaker
$ Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
💡 Note: "the" appears 4 times, "is" appears 3 times, "sunny" appears 2 times, "day" appears 1 time. All have different frequencies so lexicographical order within same frequency doesn't apply here.
Example 3 — Same Frequency Sorting
$ Input: words = ["i","love","coding"], k = 2
Output: ["coding","i"]
💡 Note: All words appear once, so we sort lexicographically: "coding" < "i" < "love". Taking first 2 gives ["coding","i"].

Constraints

  • 1 ≤ words.length ≤ 500
  • 1 ≤ k ≤ number of unique words
  • words[i] consists of lowercase English letters only
  • 1 ≤ words[i].length ≤ 10

Visualization

Tap to expand
Top K Frequent Words INPUT words array: "i" "love" "leetcode" "i" "love" "coding" k = 2 6 words total Input Values: words = ["i","love", "leetcode","i","love", "coding"] k = 2 ALGORITHM STEPS 1 Build Hash Map Count frequency of each word "i": 2 "love": 2 "leetcode": 1 "coding": 1 2 Sort by Frequency Descending order 3 Lexicographic Tiebreak Same freq: sort alphabetically 1. "i" (2) -- a-z first 2. "love" (2) 4 Return Top K Take first k elements FINAL RESULT Top 2 Most Frequent Words: "i" frequency: 2 "love" frequency: 2 Output: ["i", "love"] OK - Verified! Key Insight: Hash Map enables O(n) frequency counting. For ties (same frequency), lexicographic ordering ensures deterministic results. Time: O(n log n) for sorting. Space: O(n) for hash map storage. TutorialsPoint - Top K Frequent Words | Hash Map Approach
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
89.6K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen