Most Common Values with First-Seen Tie-Breaking
Arrays & HashingAuto-graded · 22 test casesLast updated
Return the k most frequent values in an integer list, ordered by count and then by first appearance, using hash counting and frequency buckets for linear time.
You are given a list of integers values and a positive integer k. Return the k values that occur most often in values, as a list in a specific order.
Ordering rules
The returned list must follow these rules exactly:
- Values with a higher number of occurrences come first.
- If two values occur the same number of times, the one whose first occurrence in
valueshas the smaller index comes first.
Each distinct value appears at most once in the output, and the output has exactly k elements.
Goal
Aim for an average-case running time of O(n) and O(n) extra space, where n is the length of values. Think about how the possible frequencies are bounded, and how you can group values by frequency without a comparison sort.
Constraints
1 <= len(values)- Values may be negative, zero, or positive, and may span a very large range, so do not index arrays by value.
1 <= k <= number of distinct values in values- The output is a list of
kintegers ordered as described above.
Examples
Example 1
Input: most_common_values([1, 1, 1, 2, 2, 3], 2)
Output: [1, 2]
Example 2
Input: most_common_values([4, 4, -1, -1, -1, 2, 2, 3], 2)
Output: [-1, 4]
Example 3
Input: most_common_values([5], 1)
Output: [5]
Hints
Hint 1
Count how often each value occurs with a hash map, and remember the order in which distinct values were first seen.
Hint 2
No value can occur more than n times, so you can create buckets indexed by frequency (0 to n) instead of sorting.
Hint 3
Place each distinct value in the bucket for its count, in first-seen order, then scan buckets from highest frequency to lowest and stop once you have k values.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Count. Walk through
valuesonce, building a hash map from value to count. The first time a value is seen, also append it to a listorder, which records distinct values in first-appearance order. - Bucket by frequency. A count is always between 1 and
n, so createn + 1empty buckets, where bucketfholds the values that occur exactlyftimes. Iterate overorderand append each value to the bucket for its count. Becauseorderis in first-appearance order, each bucket is automatically in the required tie-break order. - Collect. Scan the buckets from frequency
ndown to 1, appending values to the result until it haskitems, then return.
Why it is correct
- After step 1, each count is exact, and each distinct value lands in exactly one bucket.
- Scanning from high to low frequency visits values in non-increasing count order, so the first
kcollected have counts at least as large as any value left out. - Within one bucket, values are in first-occurrence order, which matches the tie-break rule.
- Since
kdoes not exceed the number of distinct values, the scan always findskvalues.
Negative numbers and huge value ranges cause no trouble because values are only used as hash-map keys; the buckets are indexed by frequency, which is bounded by n.
Complexity
- Time: O(n) on average (hash operations are O(1) on average; building buckets and scanning are O(n)).
- Space: O(n) for the map, the order list, and the buckets.
Alternative
A min-heap of size k over the distinct values works in O(n + d log k) time with O(k) extra space beyond the map (where d is the number of distinct values). It is preferable when k is small and memory matters, or when data arrives as a stream. Use the key (count, -first_index) to reproduce the same tie-break, then sort the survivors at the end.
Reference solution
from typing import List
def most_common_values(values: List[int], k: int) -> List[int]:
counts = {}
order = []
for v in values:
if v not in counts:
counts[v] = 0
order.append(v)
counts[v] += 1
buckets = [[] for _ in range(len(values) + 1)]
for v in order:
buckets[counts[v]].append(v)
result = []
for freq in range(len(values), 0, -1):
for v in buckets[freq]:
result.append(v)
if len(result) == k:
return result
return result