Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Top K Frequent Elements

mediumhash-mapheapbucket-sort

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.
  • k is at least 1 and never exceeds the number of distinct values.

Examples

  • nums = [7, 3, 7, 9, 3, 7, 2], k = 2 → [7, 3]. 7 appears three times, 3 twice, 9 and 2 once 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; -2 wins with three occurrences against two for 6.

Hints

  1. First reduce the problem to a table of value -> count; everything else operates on that table.
  2. You need the k largest counts, not a full sort of all counts.
  3. 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