AlgoFrames

Top k frequent values

Standard · Write code · about 15 min

Return the k values that appear most often in nums. Order them by count, highest first. When two values have the same count, the smaller value comes first.

Count with a hash map, then keep a min-heap of at most k (count, value) pairs.

Example 1

Input:

[[1,1,1,2,2,3],2]

Output:

[1,2]

1 appears 3 times and 2 appears twice.

Example 2

Input:

[[4,6,4,6,5],2]

Output:

[4,6]

4 and 6 both appear twice; 4 is smaller, so it comes first.

Constraints

  • 1 ≤ nums.length ≤ 10,000
  • -1,000 ≤ nums[i] ≤ 1,000
  • 1 ≤ k ≤ the number of distinct values

Learn the idea first: Priority queues in practice: top-k, k-way merge, scheduling, a visual lesson.

More Priority queues in practice: top-k, k-way merge, scheduling problems