Return the Top K Most Frequent Elements
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Implement `top_k_frequent(values, k)`.
Return the `k` distinct integers that occur most often. Order the result by decreasing frequency; when two values have the same frequency, place the value whose first occurrence in the input is earlier first. `k` is positive and does not exceed the number of distinct values.
Target `O(n)` time by using the fact that no value can occur more than `n` times.
```hint Use frequency as an array index
Count values in a hash map, then place each distinct value into a bucket whose index is its frequency.
```
```hint Make tied buckets deterministic
After counting, scan the original input once more. The first time each value is encountered, append it to its frequency bucket; equal-frequency values will then retain first-occurrence order without a comparison sort.
```
### Discussion Extensions
- Compare bucket selection with full sorting and a size-`k` heap.
- For a continuous stream, what additional structure would let frequency changes update a maintained top set without rebuilding all buckets?
Quick Answer: Return the k most frequent distinct integers with deterministic ordering for frequency ties. Combine a frequency map with buckets populated in first-occurrence order to reach O(n) time without comparison sorting.
Given an integer list and k, return the k distinct values with the highest frequencies. Order by decreasing frequency, breaking ties by the value's first occurrence in the input.
Constraints
- 1 <= values.length <= 5,000.
- 1 <= k <= the number of distinct values.
- Every value is an integer in the inclusive range [-10^12, 10^12].
- The returned order is deterministic: frequency descending, then first occurrence ascending.
Examples
Input: ([1], 1)
Expected Output: [1]
Explanation: A singleton is the only distinct value.
Input: ([1, 1, 2, 2, 3], 2)
Expected Output: [1, 2]
Explanation: Equal frequencies retain first-occurrence order.
Hints
- A value's frequency cannot exceed the input length, so frequency itself can index a collection of groups.
- Preserve the order in which distinct values first appear when placing them into equal-frequency groups.