TRT
Sign in
mediumCoreLeetCode#count then heap#bucket by frequency

Top k frequent elements

Return the k most frequent values, by counting with a hash map and keeping a size-k heap of counts.

The Runtime Theory Team1 min read
Taught inTop-k and merging streamsPro — members onlyA heap of just k items finds the k largest of a billion in one pass. A heap of k stream heads merges k sorted streams. Two heaps keep a running median. These three patterns cover most heap problems.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 1, 1, 2, 2, 3], k = 2

out[1, 2]

innums = [1], k = 1

out[1]

innums = [4, 4, 5, 5, 6], k = 2

out[4, 5]

Given an array and k, return the k most frequent elements, in any order. The answer is guaranteed to be unique.

Before you code

This is two steps: count each value, then pick the top k counts. The second step is exactly the size-k heap.

Hints

  1. Count with a hash map (collections.Counter).
  2. Keep a min-heap of (count, value) with at most k entries: O(n log k).
  3. Linear alternative: bucket the values by count (a list of lists indexed by frequency, up to n) and read buckets from the highest down.

Production & complexity notes

When solving Top k frequent elements on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Top-k and merging streams to reinforce the underlying pattern.

What it practices

Top k over derived values, from Top-k and merging streams.

Not started

Sign in to save your learning progress.

Sign in to save