Skip to Content

Top K Frequent Elements

Home | Coding Interviews | Stacks and Queues | Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

#Heap/priority queue solution
def topKFrequent_heap(self, nums: List[int], k: int) -> List[int]:
    result = []
    max_heap = [(-val, key) for key,val in collections.Counter(nums).items()]
    heapq.heapify(max_heap)
    for _ in range(k):
        result.append(heapq.heappop(max_heap)[1])
    return result

#Bucket Sort style solutions
class BucketSortSolution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        cnt = Counter(nums)
        buckets = [[] for _ in range(len(nums) + 1)]
        for val, freq in cnt.items():
            buckets[freq].append(val)
        
        return list(chain(*buckets[::-1]))[:k]

class BucketSortSolution2:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        cnt = Counter(nums)
        buckets = [[] for _ in range(len(nums) + 1)]
        for val, freq in cnt.items():
            buckets[freq].append(val)
        
        res = []
        for bucket in reversed(buckets):
            for val in bucket:
                res.append(val)
                k -=1
                if k == 0:
                    return res

Heap solution:

Bucket sort solution:

Posted by Jamie Meyer 7 months ago

Related Problems

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

MinStack() initializes the stack object.

void push(int val) pushes the element val onto the stack.

void pop() removes the element on the top of the stack.

int top() gets the top element of the stack.

int getMin() retrieves the minimum element in the stack.

You must implement a solution with O(1) time complexity for each function.

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.