Select the k Most Common Values with Tie Rules
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Count value frequencies and pick the k most frequent values, using a bounded heap and a defined tie-break rule for equal counts.
You are given a list of integers values and a non-negative integer k. Return the k values that occur most often in the list.
Selection rule
Rank the distinct values by the pair (count, value), where count is the number of times the value appears. A higher count ranks higher. If two values have the same count, the larger value ranks higher. Return the k highest-ranked distinct values.
This rule makes the chosen set unique. For example, if only one slot remains and 3 and 4 both appear once, 4 is chosen.
Output
- Return a list of the selected values.
- The order of the values inside the returned list is not significant.
- If
kis0or the input is empty, return an empty list. - If
kis at least the number of distinct values, return every distinct value. - Negative numbers are ordinary values and need no special handling.
Constraints
valuescontains integers, possibly negative and possibly repeated. It may be empty.k >= 0, andkmay be larger than the number of distinct values.- Aim for roughly
O(n + m log k)time, wheren = len(values)andmis the number of distinct values, and avoid sorting all distinct values whenkis small.
Examples
Example 1
Input: select_top_frequent([1, 1, 1, 2, 2, 3], 2)
Output: [2, 1]
Example 2
Input: select_top_frequent([4, 4, -1, -1, -1, 2, 2, 2, 2], 2)
Output: [-1, 2]
Example 3
Input: select_top_frequent([5], 1)
Output: [5]
Example 4
Input: select_top_frequent([1, 2, 3, 4], 2)
Output: [3, 4]
Hints
Hint 1
Start by counting how often each value appears with a hash map. After that, you only need to deal with the distinct values.
Hint 2
You don't need to sort all distinct values. Keep a min-heap of at most k candidates keyed by (count, value) and evict the smallest whenever it grows beyond k.
Hint 3
Tuples compare lexicographically, so (count, value) in a min-heap already evicts the lower count first and, on equal counts, the smaller value. This gives the required tie rule. Check k = 0 and k larger than the number of distinct values.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Count. Make one pass over
valuesand build a hash map from each value to its number of occurrences. - Select. Keep a min-heap of at most
kentries of the form(count, value). For each distinct value, push its pair. If the heap now holds more thankentries, pop the smallest.
The root of the heap is always the weakest of the current candidates, so popping it discards the entry that cannot be among the top k.
Why it is correct
After processing any subset of the distinct values, the heap holds the best min(k, processed) of them under the ordering (count, value). Adding one pair and removing the minimum when the size reaches k + 1 preserves this, because the minimum of k + 1 candidates cannot belong to the top k of those candidates. Once every distinct value has been processed, the heap holds the global top k.
Python compares tuples lexicographically, so on equal counts the smaller value is the smaller tuple and is evicted first. This gives the required tie rule: the larger value wins. Negative numbers compare correctly inside tuples.
Edge cases follow naturally:
- Empty input: the counter is empty, so the result is
[]. k = 0: every push is followed by a pop, so the result is[].kat least the number of distinct values: nothing is ever popped, so all distinct values are returned.
Complexity
Let n = len(values) and m be the number of distinct values.
- Time:
O(n + m log k). - Space:
O(m)for the counter plusO(k)for the heap.
An alternative is bucket sort by frequency. Build n + 1 buckets indexed by count and scan from the highest count downward. That is O(n) time, but it needs an explicit tie-break inside each bucket to match the rule above.
Reference solution
from collections import Counter
import heapq
from typing import List
def select_top_frequent(values: List[int], k: int) -> List[int]:
counts = Counter(values)
heap = []
for value, frequency in counts.items():
heapq.heappush(heap, (frequency, value))
if len(heap) > k:
heapq.heappop(heap)
return [value for frequency, value in heap]