Python coding

The k most frequent values

Given a list of integers nums and an integer k, return the k values that appear most often, in any order. k is between 0 and the number of distinct values, and the tests never have a tie at the k-th place, so the answer is unique.

Aim to beat sorting every count when k is small.

Besides the tests, one large input (10,500 numbers, k = 3,500) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • top_k_frequent([1,1,1,2,2,3], 2) → [1,2]
  • top_k_frequent([4], 1) → [4]
  • top_k_frequent([4,4,1,1,1,2,2,2,2,3], 3) → [2,1,4]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Count with a dict or Counter first; the question then becomes a top-K by count.

Hint 2

Keep a min-heap of (count, value) and pop whenever it grows past k: the root is the weakest candidate.

Solution and why it works
pythonO(n + u log k), u = distinct values · O(u)
import heapq
from collections import Counter


def top_k_frequent(nums: list[int], k: int) -> list[int]:
    heap = []
    for value, n in Counter(nums).items():
        heapq.heappush(heap, (n, value))
        if len(heap) > k:
            heapq.heappop(heap)
    return [value for _, value in heap]

Counting is O(n). The top-K step keeps a min-heap capped at k, so its root is always the weakest of the current best and is evicted first. That costs O(u log k) for u distinct values, less than sorting every count when k is small. The trap: a max-heap capped at k evicts the most frequent value and keeps the wrong ones.