Top K Frequent Elements

Implement topKFrequent

Given an array of integers and an integer k, return the k values that occur most often — ordered by frequency, highest first, with ties broken by the smaller value. Sorting every distinct value by frequency works, but frequency itself is a bounded number (a value can appear at most n times), which is exactly the situation bucket sort is built for: instead of comparing values against each other, drop each one straight into the bucket matching its count, then read the buckets off from highest to lowest.

Example 1:

Input: nums = [4,4,6,6,6,2,9,9,9,9], k = 2

Output: [9,6]

Example 2:

Input: nums = [5], k = 1

Output: [5]

Example 3:

Input: nums = [8,8,8,5,5,1], k = 2

Output: [8,5]

+ 4 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 100
  • -100 ≤ nums[i] ≤ 100
  • 1 ≤ k ≤ number of distinct values in nums
  • The result is ordered by frequency, highest first; values with equal frequency are ordered by value, smallest first, so the answer is always unique

nums =

[4, 4, 6, 6, 6, 2, 9, 9, 9, 9]

k =

2