Top K Frequent Elements

Heap
Medium

Approach

Diagrams

Analysis

Time

Space

from collections import Counter
from heapq import heappush, heappop, heapify


class Solution:
    def topKFrequent(self, nums, k):
        mostFrequent = []

        counts = Counter(nums)

        maxHeap = [(-count, num) for num, count in counts.items()]
        heapify(maxHeap)

        for _ in range(k):
            count, num = heappop(maxHeap)
            mostFrequent.append(num)

        return mostFrequent

Learn

#Max Heap

Videos