Top K Frequent Words Solution
Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: [“i”, “love”, “leetcode”, “i”, “love”, “coding”], k = 2
Output: [“i”, “love”]
Explanation:
- “i” and “love” are the two most frequent words.
- Note that “i” comes before “love” due to a lower alphabetical order.
Example 2:
Input: [“the”, “day”, “is”, “sunny”, “the”, “the”, “the”, “sunny”, “is”, “is”], k = 4
Output: [“the”, “is”, “sunny”, “day”]
Explanation: “the”, “is”, “sunny” and “day” are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Input words contain only lowercase letters.
Follow up:
- Try to solve it in O(n log k) time and O(n) extra space.
Also See: Nth Ugly numbers puesudo code using min heap

SOLUTION
Program: Top K Frequent Words Solution in C++
static bool mycmp(pair<string,int> a,pair<string,int>b){
if(a.second==b.second){
return a.first<b.first;
}
return a.second>b.second;
}
vector<string> topKFrequent(vector<string>& words, int k) {
map<string,int> mp;
for(auto x:words){
mp[x]++;
}
vector<pair<string,int>> ans(mp.begin(),mp.end());
sort(ans.begin(),ans.end(),mycmp);
vector<string> res;
int i=0;
while(k--){
res.push_back(ans[i].first);
i++;
}
return res;
}
Program: Top K Frequent Words Solution in Java
class Solution {
public List topKFrequent(String[] words, int k) {
if (words == null || words.length == 0) {
return Collections.emptyList();
}
Map<String, Integer> wordMap = new HashMap<>();
for (String word : words) {
int count = wordMap.get(word) == null ? 0 : wordMap.get(word);
wordMap.put(word, ++count);
}
PriorityQueue<PElement> pq = new PriorityQueue<>(new PElementComparator());
for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
PElement p = new PElement(entry.getKey(), entry.getValue());
pq.add(p);
}
List<String> result = new ArrayList<>();
for (int i = 0; i < k; i++) {
PElement element = pq.poll();
result.add(element.word);
}
return result;
}
private static class PElement {
String word;
int count;
public PElement(String word, int count) {
this.word = word;
this.count = count;
}
public String getWord() {
return word;
}
public int getCount() {
return count;
}
}
private static class PElementComparator implements Comparator<PElement> {
public int compare(PElement p1, PElement p2) {
if (p1 == p2) {
return 0;
}
if (p1.getCount() > p2.getCount()) {
return -1;
}
if (p2.getCount() > p1.getCount()) {
return 1;
}
return p1.getWord().compareTo(p2.getWord());
}
}
}
Program: Top K Frequent Words Solution in Python
import heapq
class OppositeString:
def __init__(self, word):
self.word = word
def __lt__(self, other):
return self.word > other.word
def __eq__(self, other):
return self.word == other.word
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
wordsDict = Counter(words)
heap = []
heapify(heap)
for w in wordsDict:
heappush(heap, (wordsDict[w], OppositeString(w)))
if len(heap) > k:
heappop(heap)
ans = ['']*k
for i in range(k-1, -1, -1):
ans[i] = heappop(heap)[1].word
return ans
Amazon OA 2023 Questions with Solution
- Shopping Patterns Solution Amazon OA 2023
- Reorder Data in Log Files Solution Amazon OA 2023
- Trees Height Solution Amazon OA SDE 2023
- Counting Binary Substrings Amazon OA 2023
- Grid Connections Amazon OA 2023
- Shipment Imbalance Amazon OA 2023
- Max Profit Amazon OA 2023
- Find Lowest Price Amazon OA 2023
- Decode String Frequency Amazon OA 2023
- Simple Cipher Amazon OA 2023
- Valid Discount Coupons Amazon OA 2023 Solution
- Count Maximum Teams Amazon OA 2023
- Minimum Coin Flips Amazon OA 2023
- Max Average Stock Price Amazon OA 2023 Solution
- Robot Bounded In Circle Amazon OA 2023
- Shopping Options Amazon OA 2023 Solution
- Fill The Truck Maximum Units on a Truck Amazon OA Solution
- Maximize Score After N Operations Number Game Solution Amazon OA 2023
- Slowest Key Amazon OA 2023 Solution
- Five Star Seller Maximum Average Pass Ratio Amazon OA 2023
- Split String Into Unique Primes Amazon OA 2023 Solution
- Storage Optimization Amazon OA 2023 Solution
- Minimum Difficulty of a Job Schedule Amazon OA 2023 Solution
- Autoscale Policy Utilization Check Amazon OA 2023
- Optimal Utilization Solution Amazon OA 2023
- Merge Two Sorted Lists Solution Amazon OA 2023
- Two Sum Unique Pairs Solution Amazon OA 2023
- Amazon Music Pairs Amazon OA 2023 Solution
- Class Grouping Amazon OA 2023 Solution
- Find Max products Amazon OA 2023 Solution
- Get encrypted number Amazon OA 2023 Solution
- Find Total Imbalance Amazon OA 2023 Solution
- Find Total Power Amazon OA 2023 Solution
from collections import Counter
import heapq
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
words.sort()
word_counter = Counter(words)
top_words = word_counter.most_common(k)
return [word for word, cnt in top_words]