LeetCode 692 Top K Frequent Words

LeetCode 692 Top K Frequent Words Problem

Download Code
class Solution(object):
#     def topKFrequent(self, words, k):
#         """
#         :type words: List[str]
#         :type k: int
#         :rtype: List[str]
#         """
#         counter = collections.Counter(words)
#         res = sorted(counter.items(), cmp=cmp_frequency, reverse=True)
#         return [k for k, _ in res[:k]]

# def cmp_frequency(x, y):
#     if x[1] != y[1]:
#         return cmp(x[1], y[1])
#     return cmp(y[0], x[0])

    # def topKFrequent(self, words, k):
    #     count = collections.Counter(words)
    #     candidates = count.keys()
    #     candidates.sort(key = lambda w: (-count[w], w))
    #     return candidates[:k]

    def topKFrequent(self, words, k):
        count = collections.Counter(words)
        # Note that python heapq only support min heap
        # So, we can make the value negative to create a max heap
        heap = [(-freq, word) for word, freq in count.items()]
        heapq.heapify(heap)
        return [heapq.heappop(heap)[1] for _ in xrange(k)]
Download Top K Frequent Words.py

List of all Top K Frequent Words problems

Leetcode 692 Top K Frequent Words problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

:type k: int

:rtype: List[str]

"""

counter = collections.Counter(words)

res = sorted(counter.items(), cmp=cmp_frequency, reverse=True)

return [k for k, _ in res[:k]]

def cmp_frequency(x, y):

if x[1] != y[1]:

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.