/347. Top K Frequent Elements

347. Top K Frequent Elements

Medium
Arrays66% acceptance

Given an integer array data and an integer count, return the count most frequent values from data. The result can be in any order. Each value in the result must be unique and correspond to one of the count highest frequencies in data.

Example 1

Input: data = [5,5,6,7,7,7,8], count = 2

Output: [7,5]

Explanation: 7 appears 3 times, 5 appears 2 times, 8 appears once. Top 2 frequent: 7 and 5.

Example 2

Input: data = [9], count = 1

Output: [9]

Explanation: Only one element, so it is the most frequent.

Example 3

Input: data = [3,3,4,4,5,5,5], count = 1

Output: [5]

Explanation: 5 appears 3 times, others appear 2 times. Top 1 frequent: 5.

Constraints

  • 1 <= len(data) <= 105
  • -104 <= data[i] <= 104
  • 1 <= count <= number of unique values in data
  • The answer is guaranteed to be unique
Python (current runtime)

Case 1

Input: data = [10,10,11,12,12,12,13], count = 3

Expected: [12,10,11]

Case 2

Input: data = [20,21,21,22,22,22,23,23,23], count = 2

Expected: [22,23]

Case 3

Input: data = [100,101,102,103,104,105], count = 6

Expected: [100,101,102,103,104,105]

Case 4

Input: data = [-1,-1,-2,-2,-2,-3], count = 1

Expected: [-2]

Case 5

Input: data = [0,0,0,1,1,2], count = 2

Expected: [0,1]