Top K Frequent
Given an integer array nums and an integer k, return the k most frequent elements.

30:00

Top K Frequent
medium
Topics
Companies

Given an integer array nums and an integer k, return the k most frequent elements.

Example 1:
Input: {"nums":[1,1,1,2,2,3],"k":2}
Output: [1,2]
Constraints:
  • 1nums.length1051 \leq \text{nums.length} \leq 10^5

  • 104nums[i]104-10^4 \leq \text{nums}[i] \leq 10^4

  • kk is in the range [1,number of unique elements in nums][1, \text{number of unique elements in nums}].

  • It is guaranteed that the answer is unique.

Input
arr ={"nums":[1,1,1,2,2,3],"k":2}
Input Array (k=2)101112232435
Frequency Map (Num -> Count)

Empty

Buckets (Index = Frequency)
1:
[]
2:
[]
3:
[]
4:
[]
5:
[]
6:
[]
Variables
No variables to display
DepthFunction Call
1topKFrequent(nums=[6], k=2)
0/12