# LeetCode 692Top K Frequent Words

## LeetCode 692 Top K Frequent Words Problem

``````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 != y:
#         return cmp(x, y)
#     return cmp(y, x)

# 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) for _ in xrange(k)]
``````

## 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 != y:

Feedback is the most important part of any website.