Skip to main content
CodeOath
← All problems

Problem

Top K Frequent Elements

Medium
  • arrays
  • hash-table
  • heap

Count how often each value occurs in nums, and return the k values with the highest counts. The order of the values in the result does not matter.

Example 1
Input
nums = [4, 4, 7, 9, 9, 9, 4, 9, 2], k = 2
Output
[9, 4]
Explanation

9 occurs four times, 4 three times, and 7 and 2 once each, so 9 and 4 are the top two. Any order is accepted, so [4, 9] is also correct.

Example 2
Input
nums = [2, 6, 9, 6, 2], k = 3
Output
[2, 6, 9]
Explanation

k equals the number of distinct values, so every value is returned.

Constraints:

  • 1 <= nums.length <= 10^5
  • k is always valid: 1 <= k <= d, where d is the number of distinct values in nums

Follow-up: sorting all the distinct values by count is a valid answer. Can you do better when k is much smaller than d?

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.