codejump
MediumPythonJavaScriptTypeScript

Heap — Top K Frequent Elements

Data StructuresHeapHash Table

Return the k most frequent values in nums.

Output order (deterministic)

  • Most frequent first.
  • Ties are broken by the smaller value first.

Sorting every distinct value is O(d log d). The point of this exercise is to do
better when k is small: count with a hash table, then keep only the best
k with a size-k min-heap (O(d log k)), or with a bucket sort (O(n)).

Examples

solve([1, 1, 1, 2, 2, 3], 2)        → [1, 2]
solve([1], 1)                       → [1]
solve([4, 4, 5, 5, 6], 2)           → [4, 5]     // 4 and 5 tie, smaller first
solve([-1, -1, 2, 2, 3], 3)         → [-1, 2, 3]

Constraints

  • 1 <= k <= the number of distinct values.

Sample tests

Test #1The classic example
Input: [[1,1,1,2,2,3],2]
Output: [1,2]
Test #2A single element
Input: [[1],1]
Output: [1]
Test #3A tie between 4 and 5 — smaller value first
Input: [[4,4,5,5,6],2]
Output: [4,5]