Skip to the solution
MediumDSA13 min read

How do you find the top K frequent elements?

175 views

The problem

Question presented to candidate: "Given a list of integers and a number k, return the k values that appear most often. If two values appear the same number of times, put the smaller value first. Write it in Python and tell me the complexity."

What a strong answer should cover:

  • Two steps: count with a hash map in O(n), then pick the k biggest counts.
  • Three ways to pick: sort the m distinct values (O(m log m)), a size-k min-heap (O(m log k)), or bucket sort by count (O(n)) because a count is at most n.
  • Ties: encode the rule in the key โ€” here the heap key (count, -value) makes the weakest entry the lowest count, then the larger value.
  • Edge cases: k equal to the number of distinct values, ties at the cut-off, negative numbers.
  • Python specifics: collections.Counter, and that Counter.most_common(k) breaks ties by first appearance, not by value; heapq is a min-heap, so tuples (count, -value) give the right weakest-first order; heapq.nlargest(k, counts, key=...) as the one-liner.

Clarifying questions expected:

  • How should ties be ordered, and must the result be sorted by frequency?
  • Is k always at most the number of distinct values?

Code / implementation expected: Yes โ€” Counter plus a size-k heapq, and the bucket-sort version if asked for O(n), in Python.

  • heap
  • top-k

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTop K frequent with a hash map + size-k min-heap (ties: smaller value first)
PythonSorting vs heap vs bucket sort on 200,000 skewed values

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 119 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the Kth largest element โ€” heap vs quickselect, and when to choose which?

Continue