Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return top K frequent elements

The task is to return the K most frequent elements.
What I did is to calculate the frequencies and put it in a min-heap (as we know there’s no max-heap in Python), then I need to heappop k times.

from collections import defaultdict
import heapq

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        counts = defaultdict(int)
        for i in range(len(nums)):
            counts[nums[i]] -= 1
            
        counts = list(counts.items())
        heapq.heapify(counts)
        top_k = [heapq.heappop(counts)[0] for i in range(k)]
        return top_k
            
        

Why does my code fails on topKFrequent([4,1,-1,2,-1,2,3], 2)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using collectons.Counter would be a lot easier:

return list(dict(sorted(Counter(nums).items(), key=lambda x:x[1])).keys())[:k]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading