Hash map · Medium
A dashboard summarizes which numeric event codes occur most often. It displays only k distinct codes. The display must be deterministic when several codes have the same frequency.
Return the k most frequent distinct values ordered by descending count and then ascending numeric value.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "nums": number[], "k": number }.
Fields
- nums contains integer event codes. k is an integer between zero and the number of distinct values inclusive.
Output
Return value
- Return an array of distinct values, not [value,count] pairs.
- Use numeric ascending order on ties, including negatives.
- For k=0 return []. Empty nums therefore has k=0.
Constraints
- At most 100000 values, each an integer in [-1000000000,1000000000].
Examples
Example 1
{
"k": 2,
"nums": [
3,
1,
3,
1,
2
]
}Returns
[
1,
3
]Both occur twice; 1 wins the tie.
Example 2
{
"k": 3,
"nums": [
10,
2,
-1
]
}Returns
[
-1,
2,
10
]Ties use numeric rather than string sorting.
Required complexity
O(n + d log(d + 1)) time and O(d) space is accepted; a bounded heap is optional