Top K Frequent Words Solution Amazon OA 2023

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:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters.

Follow up:

  1. 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

Top K Frequent Words Amazon Online Assessment
Top K Frequent Words Amazon Online Assessment

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

  1. Shopping Patterns Solution Amazon OA 2023
  2. Reorder Data in Log Files Solution Amazon OA 2023
  3. Trees Height Solution Amazon OA SDE 2023
  4. Counting Binary Substrings Amazon OA 2023
  5. Grid Connections Amazon OA 2023
  6. Shipment Imbalance Amazon OA 2023
  7. Max Profit Amazon OA 2023
  8. Find Lowest Price Amazon OA 2023
  9. Decode String Frequency Amazon OA 2023
  10. Simple Cipher Amazon OA 2023
  11. Valid Discount Coupons Amazon OA 2023 Solution
  12. Count Maximum Teams Amazon OA 2023
  13. Minimum Coin Flips Amazon OA 2023
  14. Max Average Stock Price Amazon OA 2023 Solution
  15. Robot Bounded In Circle Amazon OA 2023
  16. Shopping Options Amazon OA 2023 Solution
  17. Fill The Truck Maximum Units on a Truck Amazon OA Solution
  18. Maximize Score After N Operations Number Game Solution Amazon OA 2023
  19. Slowest Key Amazon OA 2023 Solution
  20. Five Star Seller Maximum Average Pass Ratio Amazon OA 2023
  21. Split String Into Unique Primes Amazon OA 2023 Solution
  22. Storage Optimization Amazon OA 2023 Solution
  23. Minimum Difficulty of a Job Schedule Amazon OA 2023 Solution
  24. Autoscale Policy Utilization Check Amazon OA 2023
  25. Optimal Utilization Solution Amazon OA 2023
  26. Merge Two Sorted Lists Solution Amazon OA 2023
  27. Two Sum Unique Pairs Solution Amazon OA 2023
  28. Amazon Music Pairs Amazon OA 2023 Solution
  29. Class Grouping Amazon OA 2023 Solution
  30. Find Max products Amazon OA 2023 Solution
  31. Get encrypted number Amazon OA 2023 Solution
  32. Find Total Imbalance Amazon OA 2023 Solution
  33. Find Total Power Amazon OA 2023 Solution

1 thought on “Top K Frequent Words Solution Amazon OA 2023”

  1. 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]

Comments are closed.