AceYourInterviews
Checking sign-in…

70. Top K Frequent Elements

CoreFrequency ranking with a worst-retained frontier

Count how often each distinct input value occurs and select the k values with the greatest counts. Report the selected values rather than their individual occurrences.

This course orders the result by decreasing frequency, then increasing numeric value for ties. Do not assume arbitrary tie order is accepted.

Example 1

Input

nums=[4,4,1,1,2,3], k=2

Output

[1,4]

Explanation: Both 1 and 4 occur twice, so smaller value 1 precedes 4.

Example 2

Input

nums=[−1,−1,2,3], k=3

Output

[−1,2,3]

Explanation: Frequency outranks numeric magnitude. The final two keys tie at count one.

Example 3

Input

nums=[], k=0

Output

fresh []

Explanation: The rank set is empty and no value sentinel is needed.

Constraints

  • 0 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= number of distinct values
Hints
Hint 1

How many times does each distinct key occur?

Hint 2

Which selected candidate should be easiest to evict when the heap exceeds k?

Hint 3

Use the reverse of the final count/value rank for the heap root, trim after each insertion, and sort the survivors.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Count ties select smaller values

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