Skip to content
BASA DSA

Top K Frequent Elements

MediumArrays & Hashing

Return the k distinct values with highest frequencies in nums, in any order.

Example 1

Input
nums = [4,4,4,2,2,9]
k = 2
Output
[4,2]

Explanation

4 occurs three times and 2 twice, exceeding the single occurrence of 9.

Example 2

Input
nums = [-1,-1,2]
k = 1
Output
[-1]

Explanation

-1 occurs twice, so it beats 2 regardless of numeric ordering.

Example 3

Input
nums = [8]
k = 1
Output
[8]

Explanation

There is only one distinct value and k is one, so return 8.

Constraints

  • 1 <= k <= number of distinct values <= 100000
  • The frequency boundary at k has no tie

Function contracttopKFrequentArguments: json, json
Loading draft…
SolutionRuns on your device
Loading draft…