MediumBlind75ArrayHash TableHeap

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.

Examples

Input
nums = [1,1,1,2,2,3], k = 2
Output
[1,2]

Element 1 appears 3 times, element 2 appears 2 times.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, the number of unique elements in the array]
  • It is guaranteed that the answer is unique.

Approaches

Count frequencies, then sort by frequency and return the top k.

CodeT: O(n log n) | S: O(n)
def top_k_frequent(nums, k):
    from collections import Counter
    count = Counter(nums)
    sorted_items = sorted(count.items(), key=lambda x: x[1], reverse=True)
    return [item[0] for item in sorted_items[:k]]

Use a min heap of size k to keep track of the k most frequent elements.

CodeT: O(n log k) | S: O(n + k)
def top_k_frequent(nums, k):
    from collections import Counter
    import heapq
    count = Counter(nums)
    return heapq.nlargest(k, count.keys(), key=count.get)

Use bucket sort where index represents frequency. Collect from highest bucket.

Diagram

nums=[1,1,1,2,2,3], k=2 count={1:3, 2:2, 3:1} buckets: [[], [3], [2], [1], [], [], []] Collect from end: freq 3->[1], freq 2->[1,2], k=2 done
CodeT: O(n) | S: O(n)
def top_k_frequent(nums, k):
    from collections import Counter
    count = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]
    for num, freq in count.items():
        buckets[freq].append(num)
    result = []
    for i in range(len(buckets) - 1, -1, -1):
        for num in buckets[i]:
            result.append(num)
            if len(result) == k:
                return result
    return result

Complexity Comparison

Sorting by Frequency
T: O(n log n)S: O(n)

Count frequencies, then sort by frequency and return the top k.

Min Heap
T: O(n log k)S: O(n + k)

Use a min heap of size k to keep track of the k most frequent elements.

Bucket Sort
T: O(n)S: O(n)

Use bucket sort where index represents frequency. Collect from highest bucket.

Common Mistakes

Using a max heap when a min heap of size k is more efficient

Forgetting that bucket sort works because max frequency is at most n

Not handling the case where multiple elements have the same frequency

Try It Yourself

Copy the optimal solution and run it in our compiler.

Open in Compiler