Return the K Most Frequent Values with a Larger-Value Tie-Break
Company: Oracle
Role: Backend Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
## Problem
Given an integer array and an integer `k`, return the `k` distinct values with the highest frequencies. Sort the result by descending frequency. If two values have equal frequency, place the larger value first.
### Function Contract
Implement `topKFrequentWithTieBreak(values, k)` and return an integer array.
### Constraints & Assumptions
- `1 <= len(values) <= 200,000`.
- Values are integers in the signed 32-bit range.
- `1 <= k <= number of distinct values`.
- The output order is part of the contract.
### Clarifying Questions to Ask
- Are duplicate values counted separately? Yes, each occurrence contributes to frequency.
- What resolves a frequency tie? The numerically larger value comes first.
- Must the full set of distinct values be sorted? No; an efficient bounded selection is acceptable.
```hint Give the heap the inverse priority
When retaining only `k` candidates, the root should be the worst retained candidate: lower frequency first, and for an equal frequency, smaller value first.
```
### Examples
```text
values = [1,1,1,2,2,3], k = 2 -> [1,2]
values = [4,4,3,3,2], k = 2 -> [4,3]
values = [-1,-1,2,2], k = 2 -> [2,-1]
```
### Evaluation Focus
- Counts every distinct value accurately.
- Applies the larger-value tie-break both during selection and final ordering.
- Returns exactly `k` values.
- Achieves `O(n + m log k)` time for `m` distinct values, or justifies another efficient bound.
### Extensions to Discuss
1. How would you maintain the answer over a continuous event stream?
2. What changes if the tie-break is earliest first occurrence?
3. When is bucket sorting preferable to a heap?
Overview: Return the `k` most frequent distinct integers ordered by descending frequency, with larger values ranked first whenever frequencies tie.
Read the full Oracle Backend Engineer interview experience this question came from
Return the k distinct integer values with greatest frequency. Order by decreasing frequency, breaking equal frequencies by larger numeric value first.
Constraints
- 1 <= len(values) <= 200000.
- Values are signed 32-bit integers.
- 1 <= k <= number of distinct values.
- Equal frequencies favor the larger value.
Examples
Input: ([1, 1, 1, 2, 2, 3], 2)
Expected Output: [1, 2]
Explanation: Frequency decides both positions.
Input: ([-1, -1, 2, 2], 2)
Expected Output: [2, -1]
Explanation: Larger value wins a frequency tie.
Hints
- Count first, then apply the same comparator to every distinct value.
- The output comparator is frequency descending then value descending.