Skip to contentKEEP THE CRAFTTHE SANCTUARY

Top K Frequent Elements

Count each value, group values by how often they appear, and read the groups from most to least frequent.

The problem

Implement Solution.topKFrequent(nums, k). Return the k values that appear most often in nums, as a list of ints in any order. The answer is guaranteed to be unique: there is never a tie for the last place. nums has 1 to 100,000 integers between -10,000 and 10,000, and k is between 1 and the number of distinct values.

Starter code

class Solution:
    def topKFrequent(self, nums, k):
        pass

Public examples

  1. nums = [1, 1, 1, 2, 2, 3], k = 2gives[1, 2]
  2. nums = [-5, -5, -5, 2, 2, 9], k = 1gives[-5]
  3. nums = [7, 2, 9], k = 3gives[7, 2, 9]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.