Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Top K Frequent Elements
Problem
Given an integer array nums and an integer k, return the k values that occur most often in nums. The input is such that exactly one set of k values qualifies, and you may return them in any order.
- The array is non-empty and has at most 200,000 elements.
- Values are small integers; magnitudes stay under 50,000.
kis at least 1 and never exceeds the number of distinct values.
Examples
nums = [7, 3, 7, 9, 3, 7, 2], k = 2→[7, 3].7appears three times,3twice,9and2once each.nums = [11], k = 1→[11]. One distinct value.nums = [-2, -2, 6, 6, 0, -2], k = 1→[-2]. Negative values count like any other;-2wins with three occurrences against two for6.
Hints
- First reduce the problem to a table of
value -> count; everything else operates on that table. - You need the k largest counts, not a full sort of all counts.
- Either a min-heap of size k, or bucket the values by count (counts are bounded by n) and read buckets from the top.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.