← Back to Algorithms, page 1

algorithms-0006 · Medium mid

Top K frequent elements: return the k most frequent values in a list in better than O(n log n) time.

Count frequencies with a dictionary, then avoid a full sort. A min-heap of size k gives O(n log k). Bucket sort by frequency gives O(n): make a list of buckets indexed by count from 0 to n, put each value in the bucket for its count, and read buckets from the highest count down until you have k values.

Full answer

Problem

Given nums and k, return the k values that occur most often, in any order.

Example: nums = [1, 1, 1, 2, 2, 3], k = 2 gives [1, 2].

Constraints: 1 <= len(nums) <= 10^5, 1 <= k <= number of distinct values. The answer is unique (no ties at the boundary).

Brute force

Count with a dictionary, sort the distinct values by count, take the first k. O(n + d log d) where d is the number of distinct values, which is O(n log n) when most values are distinct.

Better: heap

Keep a min-heap of (count, value) of size k. Push each distinct value; if the heap exceeds k, pop the smallest. O(n + d log k). heapq.nlargest(k, counts, key=counts.get) does this in one line. Good when k is much smaller than d.

Optimal: bucket sort by frequency

A value's count is between 1 and n. Create n + 1 buckets, where buckets[c] lists values seen exactly c times. Then walk from c = n down to 1 and collect values until there are k.

Why it works

Bucket index equals frequency, so reading buckets from high to low visits values in decreasing order of frequency without comparing them. Every value lands in exactly one bucket and the walk touches each bucket once, so the work is O(n).

Complexity

Bucket sort: O(n) time, O(n) space. Heap: O(n + d log k) time, O(d + k) space.

Code

python
from collections import Counter


def top_k_frequent(nums, k):
    """Return the k most frequent values using bucket sort by frequency. O(n)."""
    freq = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]   # index = frequency
    for value, count in freq.items():
        buckets[count].append(value)
    result = []
    for count in range(len(buckets) - 1, 0, -1):
        for value in buckets[count]:
            result.append(value)
            if len(result) == k:
                return result
    return result


if __name__ == "__main__":
    assert sorted(top_k_frequent([1, 1, 1, 2, 2, 3], 2)) == [1, 2]
    assert top_k_frequent([4], 1) == [4]
    assert sorted(top_k_frequent([5, 5, 6, 6, 7], 2)) == [5, 6]
    assert sorted(top_k_frequent([3, 1, 2], 3)) == [1, 2, 3]
    assert top_k_frequent([-1, -1, 2], 1) == [-1]
    print("all tests passed")

Save as a06_top_k_frequent.py and run python3 a06_top_k_frequent.py. It prints all tests passed (Python 3.13.5).

Edge cases

k equal to the number of distinct values (return all). A single element. Negative numbers (dictionary keys, no issue). Ties at the boundary: clarify whether any tied value is acceptable; this implementation returns them in bucket order.

Pattern

Counting plus bucket sort: when the sort key is a small bounded integer (here a frequency at most n), place items directly by key instead of comparing. For streaming data where n is unknown, the heap or a heavy-hitters sketch (Count-Min) is used instead.

python
from collections import Counter


def top_k_frequent(nums, k):
    """Return the k most frequent values using bucket sort by frequency. O(n)."""
    freq = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]   # index = frequency
    for value, count in freq.items():
        buckets[count].append(value)
    result = []
    for count in range(len(buckets) - 1, 0, -1):
        for value in buckets[count]:
            result.append(value)
            if len(result) == k:
                return result
    return result


if __name__ == "__main__":
    assert sorted(top_k_frequent([1, 1, 1, 2, 2, 3], 2)) == [1, 2]
    assert top_k_frequent([4], 1) == [4]
    assert sorted(top_k_frequent([5, 5, 6, 6, 7], 2)) == [5, 6]
    assert sorted(top_k_frequent([3, 1, 2], 3)) == [1, 2, 3]
    assert top_k_frequent([-1, -1, 2], 1) == [-1]
    print("all tests passed")

Bucket sort by frequency after counting with collections.Counter.

Complexity

Time: O(n). Space: O(n). The heap alternative is O(n + d log k) and is preferable for streams or when n buckets would waste memory.

By level

Fresher: Counts with a dictionary, sorts by count and takes the top k, then explains how buckets avoid the sort. Should be able to explain the heap version at a high level.

Mid: Implements bucket sort or a size-k heap, compares their costs and chooses based on k and n. Can explain the tie-breaking rule when two values have the same count.

Senior: Discusses streaming heavy hitters (Count-Min sketch, Misra-Gries), distributed top-k with partial aggregation, and memory trade-offs. Can explain what changes when k is close to the number of distinct values.

Key points

  • Count first with a dictionary
  • Frequencies are bounded by n, so bucket by count
  • Read buckets from high to low until k values
  • Heap of size k gives O(n log k)
  • Clarify tie handling

Common mistakes

  • Sorting all values when only k are needed
  • Using a max-heap of all values and popping k times without noting the cost
  • Forgetting that bucket index 0 is never used
  • Ignoring ties at the boundary

Follow-ups

  • How would you do this on an infinite stream?
  • What if k is close to the number of distinct values?
  • How would you return results sorted by frequency?

Tips

  • Give the sort solution first, then the heap, then buckets
  • Explain why frequency is a bounded key
  • Mention heapq.nlargest as the practical option

Evaluation rubric

  • Correct counting and selection
  • Achieves O(n) or justifies O(n log k)
  • Explains bucket idea clearly
  • Discusses ties and streaming