Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
4,044 views

All past online assesments of Amazon can be found using the tag "amazon_oa" in the search bar.

Here is the link : https://www.desiqna.in/tag/amazon_oa

in Online Assessments by Expert (108,170 points)
edited by | 4,044 views

2 Answers

0 like 0 dislike
Best answer

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.

 

Example 1:

Input: words = ["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: words = ["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.

 

Constraints:

  • 1 <= words.length <= 500
  • 1 <= words[i] <= 10
  • words[i] consists of lowercase English letters.
  • k is in the range [1, The number of unique words[i]]
by Expert (108,170 points)
0 like 0 dislike
from heapq import heappop, heappush
import re
from typing import Counter, List

class Down:
    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        return self.value > other.value

def top_mentioned(k: int, keywords: List[str], reviews: List[str]) -> List[str]:
    patt = re.compile(r'\b(:?{})\b'.format('|'.join(keywords)), flags=re.IGNORECASE)
    counts = Counter(
        word
        for review in reviews
        for word in set(match[0].lower() for match in patt.finditer(review))
    )
    queue = []
    for word, count in counts.items():
        heappush(queue, (count, Down(word)))
        if len(queue) > k:
            heappop(queue)
    res = []
    while len(queue) > 0:
        res.append(heappop(queue)[1].value)
    return res[::-1]

if __name__ == '__main__':
    k = int(input())
    keywords = [input() for _ in range(int(input()))]
    reviews = [input() for _ in range(int(input()))]
    res = top_mentioned(k, keywords, reviews)
    print(' '.join(res))
by Expert (108,170 points)