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: Complete FlowInput: words=["i","love","leetcode","i","love","coding"], k=2"i""love""leetcode""i""love""coding"↓ Count Frequencies ↓i: 2love: 2coding: 1leetcode: 1↓ Sort: frequency desc → lexicographical asc ↓"i""love""coding"Output: ["i", "love"] (top k=2)
Understanding the Visualization
1
Input
Array of words and k value
2
Count & Sort
Count frequencies, then sort by custom rules
3
Output
Return top k words in proper order
Key Takeaway
🎯 Key Insight: Custom sorting with (-frequency, word) handles both criteria elegantly
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