KatInterview

K Most Common Values in an Array

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchhash-mapheapbucket-sort

Last updated

Tests frequency counting and top-k selection using hash maps, heaps, or bucket sort, including complexity trade-off reasoning.

K Most Common Values in an Array

You are given a list of integers and a positive integer k. Your task is to find the k values that appear most frequently across the list, returning them in any order.

The input is always valid: k is at least 1 and at most the number of distinct values present, so there will always be exactly k values to return. You are also guaranteed that no tie exists at the boundary between the k-th and (k+1)-th most frequent values, so the result set is always unambiguous.

For example, if the list is [4, 4, 4, 6, 6, 7, 7, 7, 8] and k = 2, the frequencies are: 4 → 3, 7 → 3, 6 → 2, 8 → 1. The two highest frequencies both equal 3, and they belong to 4 and 7, so the answer is [4, 7] (in either order).

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= number of distinct values in nums
  • The answer is unique: no tie exists at the k-th frequency boundary

Examples

Example 1

Input: top_k_frequent([1, 1, 1, 2, 2, 3], 2)

Output: [1, 2]

Example 2

Input: top_k_frequent([1], 1)

Output: [1]

Example 3

Input: top_k_frequent([4, 4, 4, 6, 6, 7, 7, 7, 8], 2)

Output: [4, 7]

Hints

Hint 1

Start by counting how many times each value appears. A dictionary or Counter gives you that in a single pass over the list.

Hint 2

To pick the top k entries from your frequency map, think about a min-heap of fixed size k. As you process each distinct value, keep only the k largest frequencies seen so far by evicting the smallest whenever the heap exceeds k.

Hint 3

There is an O(n) approach: since every frequency must be between 1 and n, you can create n+1 buckets indexed by frequency, place each value in its bucket, then sweep from the highest-frequency bucket downward until you have collected k values.