See my jobs
Home/Problems/Top K frequent

Top K Frequent Elements

Updated Nov 17, 2026

23 of 909 coded candidate reports (Jan 2025 to Nov 2026) mention a top-K frequency question; 15 are Meta; 1 in the last 90 days

Given a list of values, return the k that appear most often. It is a short problem with three good answers (sort, heap, bucket sort), and interviewers use the follow-ups to see how far you can take it: ties, streams, and data spread over many machines.

In short
  • 23 of 909 reports mention a top-K frequency question: Meta 15, Amazon 4, and one each from Google, Nvidia and Pinterest. Only 1 is from the last 90 days.
  • Count with a hash map first. Then a min-heap of size k gives O(n log k); bucket sort by count gives O(n).
  • Ask about ties before coding. The words version usually wants alphabetical order among equal counts, which trips up heap code.
  • Common follow-ups: a stream you cannot store, a sliding window, and counts spread across machines.
  • In AI-allowed rounds, check heap direction and tie order in generated code, and compare against a sort-based reference on random inputs.

The problem

You get a list of integers nums and a number k. Return the k distinct values that occur most often in the list, in any order. You may assume k is at least 1 and at most the number of distinct values.

Ask what happens when two values tie for the last spot. Many versions promise the answer is unique; others want a tie rule, such as smaller value first or first appearance first.

Examples

InputkOutputWhy
[4, 4, 7, 4, 9, 7, 2]2[4, 7]4 appears 3 times, 7 twice, the rest once
[5, 5, 6, 6, 6]1[6]6 appears 3 times
[-1, -1, 3]1[-1]Negative values work the same way
[8, 2, 5]2AmbiguousAll tie; ask which tie rule applies

Who asks it

We coded 909 first-hand candidate reports that list questions, dated January 2025 to November 2026. 23 mention a top-K frequency question. Counting only single-company reports: Meta 15, Amazon 4, and one each from Google, Nvidia and Pinterest. Only 1 is from the last 90 days.

Two caveats. First, our matching counts any "top K" mention, so at least four of the Meta reports are design questions (trending songs, top-K heavy hitters [9], location-based top-K) rather than the coding problem; see the leaderboard design page for those. Second, most Meta reports in our data come from LeetCode Discuss posts in early 2025, so this problem's high overall count leans on older data. The related theme of heaps and priority queues appears in 15 reports, 5 of them recent, most often Google (4) and Amazon (2).

CompanyWhat candidates describe
GoogleL4 phone screen, Sep 2026: register messages and return the most active user in O(1), with a top-K follow-up [1].
NvidiaPhone screen, Jun 2026: streaming top-K, moving from a heap to buckets [2].
PinterestJun 2026 thread about the senior phone screen: one commenter got a top-K problem in their screen [3].
Unnamed (senior to staff)May 2026: a multi-part coding problem built on a frequency map and a priority queue [4].
MetaE4 onsite, Jan 2025: the interviewer wanted the O(n) bucket approach [5]. E4 phone screen, Mar 2025: trending hashtags top K [8]. Mar 2025: k most frequent with ties broken by first appearance [7].
AmazonSDE II onsite, Apr 2025: top K frequent words [6]. SDE2, Jan 2025: priority-queue top-N where counts get updated [12].

Approach: brute force to optimal

Every approach starts by counting: one pass with a hash map from value to count, O(n) time and O(d) space for d distinct values. The difference is how you pick the top k from the counts.

ApproachTimeExtra spaceNotes
Count, then sort all distinct values by countO(n + d log d)O(d)Simplest correct answer; say it first
Count, then min-heap of size kO(n + d log k)O(d + k)Best when k is much smaller than d; also works on streams
Count, then bucket sort by countO(n)O(n)Counts are between 1 and n, so use them as array indexes
Count, then quickselect on countsO(n) average, O(d^2) worstO(d)Good to mention; harder to write bug-free

For the heap, keep the k best so far in a min-heap keyed by count. The smallest of the k sits on top. For each new value, if its count beats the top, replace the top. At the end the heap holds the k largest counts.

For bucket sort, make a list of n+1 buckets where bucket i holds values that appear exactly i times. Walk from the highest bucket down and collect values until you have k.

Python solution

from collections import Counter
import heapq


def top_k_frequent(nums: list[int], k: int) -> list[int]:
    """Bucket sort by count: O(n) time, O(n) space."""
    counts = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]   # index = frequency
    for value, freq in counts.items():
        buckets[freq].append(value)
    result = []
    for freq in range(len(buckets) - 1, 0, -1):
        for value in buckets[freq]:
            result.append(value)
            if len(result) == k:
                return result
    return result


def top_k_frequent_heap(nums: list[int], k: int) -> list[int]:
    """Min-heap of size k: O(n log k) time, O(n) space for the counts."""
    counts = Counter(nums)
    heap = []                                       # (freq, value)
    for value, freq in counts.items():
        if len(heap) < k:
            heapq.heappush(heap, (freq, value))
        elif freq > heap[0][0]:
            heapq.heapreplace(heap, (freq, value))
    return [value for _, value in sorted(heap, reverse=True)]

Present one fully and mention the other. If the interviewer cares about O(n), lead with buckets. If they hint at a stream or a huge input, lead with the heap, since it only needs the counts and k slots.

Follow-up questions

  • Top K frequent words (Amazon [6]): the usual version breaks ties alphabetically, so the sort key is (-count, word). With a size-k min-heap, the entry that should leave first is the lower count, or on equal counts the alphabetically later word, so plain (count, word) tuples order ties the wrong way. Either sort all candidates by (-count, word), or wrap words in a class with a reversed comparison.
  • Ties by first appearance (Meta [7]): record the index where each value first appears and use it as the second sort key.
  • A stream too large to store (Amazon [12], Nvidia [2]): keep counts and a size-k heap that updates as counts change, or when even the counts do not fit, use an approximate method such as Count-Min Sketch plus a heap, or the Misra-Gries algorithm. Say what error you accept.
  • Last N minutes only: bucket counts per minute, add the newest minute and subtract the expired one, then recompute the top k from the window counts.
  • O(1) most frequent with updates (Google [1]): keep value-to-count and count-to-set-of-values maps plus the current maximum, the same idea as the O(1) LFU cache.
  • Data spread across machines: first route counts so all occurrences of a value land on the same machine (partition by value hash), then take top k per machine and merge. Merging each machine's local top k without that step can miss a value that is 11th everywhere but 1st overall.
  • k close to the number of distinct values: find the d-k least frequent values with a small max-heap and return everything else, or use bucket sort, which does not care about k.

The AI-allowed version

We have no report of this exact problem in an AI-assisted round. The general pattern from those rounds still applies. Meta's careers FAQ says many interviews now include a built-in AI assistant that candidates are expected to use [10]. A Meta E6 candidate described the risk plainly: "I didn't review the AI's code carefully and didn't catch one bug, and then I just started optimizing." They were rejected [11].

For a problem this well known, the AI will produce working base code in seconds. The interview then shifts to the parts it gets wrong or that need your judgment.

  • You still choose heap vs buckets from the constraints and explain the complexity, pin down the tie rule with the interviewer, and design the streaming or distributed version.
  • In generated code, check heap direction first. Python's heapq is a min-heap, so code that pushes counts and pops k times returns the least frequent values. Then check tie order in the words version, that the function returns values and not counts, and the bucket list size, which needs n+1 slots.
  • To verify fast, keep a one-line reference, sorted(counts, key=counts.get, reverse=True)[:k], and compare the frequencies of both results on a few hundred random small lists. Compare frequencies, not exact lists, since order among ties can differ legitimately.
  • Narrate the review: say what you are checking and why, since that is what the round grades.

Common mistakes

  • Coding before asking about ties.
  • Using a max-heap of all d values and calling it O(n log k).
  • Sizing the bucket list as n instead of n+1, so a value that appears n times has nowhere to go.
  • Returning the counts, or (count, value) pairs, instead of the values.
  • In the words version, a min-heap of (count, word) that keeps the wrong word on ties.
  • Merging per-machine top-k lists in the distributed follow-up without partitioning by value first.

How to prepare

Write all three versions

Sort, heap and buckets, each in under 10 minutes, from memory, in a plain editor.

Do the words version separately

It is a different problem in practice because of the tie rule. Write it with a heap and with a sort.

Practise the stream follow-up out loud

Explain exact counts with a heap, then Count-Min Sketch when memory runs out, in under two minutes.

Practise Top K Frequent with follow-ups

A mock coding interview that moves from the base problem to ties, streams and distributed counts.

Start free mock

FAQ

Heap or bucket sort: which should I present?

Both are good. Bucket sort is O(n) and short. The heap is O(n log k), works on streams, and leads naturally into follow-ups. Mention both and ask which the interviewer prefers.

Can I use Counter.most_common(k)?

Say it exists; it uses a heap internally when k is given. Most interviewers then ask you to write the selection yourself.

Is quickselect worth writing?

Mention it for O(n) average time. Write it only if asked, since it has a bad worst case and is easy to get wrong under time pressure.

Which companies ask it?

In our data: Meta 15, Amazon 4, and one each from Google, Nvidia and Pinterest. Only one report is from the last 90 days (Google, Sep 2026) [1], and several Meta mentions are design questions rather than this coding problem.

How is this related to the leaderboard design question?

The coding problem is the single-machine core. The design version adds streams, time windows and many machines. See the top-K / leaderboard design page.

Sources

  1. Candidate report · PracHub: Google L4, most active user in O(1) and top-K · Sep 2026
  2. Candidate report · PracHub: Nvidia SWE, two phone screens incl. streaming top-K · Jun 2026
  3. Candidate report · Reddit r/leetcode: Pinterest senior SWE phone screen thread · Jun 3, 2026
  4. Candidate report · Reddit r/ExperiencedDevs: after 3 months of rejections, an offer (multi-part frequency map + priority queue) · May 23, 2026
  5. Candidate report · LeetCode Discuss: Meta E4 onsite passed (Top K Frequent, O(n) bucketing) · Jan 2025
  6. Candidate report · LeetCode Discuss: Amazon SDE II onsite (top K frequent words) · Apr 2025
  7. Candidate report · LeetCode Discuss: Meta full loop, k most frequent by first appearance · Mar 2025
  8. Candidate report · LeetCode Discuss: Meta E4 phone screen, trending hashtags top K · Mar 2025
  9. Candidate report · Blind: Meta E5 experience, top-K heavy hitters design · Sep 2025
  10. Official · Meta Careers: hiring process FAQ (built-in AI assistant)
  11. Candidate report · PracHub: Meta E6, rejected after missing a bug in AI-assisted coding · Nov 2026
  12. Candidate report · LeetCode Discuss: Amazon SDE2 Seattle, priority-queue top-N with updates · Jan 2025

We quote briefly, never name posters, and correct errors on request: report an error.

Related