K Most Common Values in an Array
Heaps, Sorting & SearchAuto-graded · 21 test casesLast 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^41 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem splits cleanly into two phases.
Phase 1 — count frequencies. A single pass with collections.Counter builds a hash map from each distinct value to the number of times it appears. This costs O(n) time and O(m) space, where n is the length of the input list and m is the number of distinct values (m ≤ n).
Phase 2 — select the k highest-frequency values. There are three standard options worth knowing:
- Sort all
(value, frequency)pairs by frequency descending and take the first k. Simple, but O(m log m) — more work than necessary. - Min-heap of size k. Maintain a heap that never grows beyond k entries, ordered by frequency. For each distinct value, push it; if the heap exceeds k, pop the minimum. What remains are the k values with the highest frequencies. Cost: O(m log k). For small k this is effectively linear.
heapq.nlargest(k, freq_map.keys(), key=freq_map.get)implements exactly this under the hood. - Bucket sort. A frequency is always an integer in [1, n]. Allocate n+1 buckets where bucket
fcollects values that appear exactlyftimes. Scan from bucket n down to bucket 1, accumulating values until you have k of them. This runs in O(n) time and O(n) space — optimal for any k.
The reference solution uses the heap path via heapq.nlargest, which is concise and efficient for typical inputs. The bucket-sort path is worth mentioning as an O(n) alternative when k can be large.
Why it is correct. Counter records exact occurrence counts. heapq.nlargest with key=freq_map.get compares entries by their true frequency and returns the k largest. The guarantee that no tie exists at the boundary means this set is unambiguous.
Edge cases handled naturally:
- A list with a single element (
k = 1) returns that element. - Negative values and zero work fine because bucket indices are frequencies, not values.
k == m(every distinct value requested) returns all keys.- Frequencies up to n are correctly captured; the bucket array must have size n+1 to index frequency n.
Complexity
| Approach | Time | Extra Space |
|---|---|---|
| Sort counts | O(n + m log m) | O(m) |
| Min-heap of size k | O(n + m log k) | O(m) |
| Bucket sort | O(n) | O(n) |
n = len(nums), m = number of distinct values.
Reference Solution
from typing import List
from collections import Counter
import heapq
def top_k_frequent(nums: List[int], k: int) -> List[int]:
# Count occurrences of every distinct value.
freq_map = Counter(nums)
# heapq.nlargest selects the k keys with the largest associated frequencies
# in O(n + m log k) time, where m is the number of distinct values.
return heapq.nlargest(k, freq_map.keys(), key=freq_map.get)
If you want to show the O(n) bucket-sort approach explicitly:
from typing import List
from collections import Counter
def top_k_frequent(nums: List[int], k: int) -> List[int]:
freq_map = Counter(nums)
# Bucket i holds all values that appear exactly i times.
buckets: List[List[int]] = [[] for _ in range(len(nums) + 1)]
for value, freq in freq_map.items():
buckets[freq].append(value)
result: List[int] = []
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