Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
💡 Note: Element 1 appears 3 times, element 2 appears 2 times, element 3 appears 1 time. The 2 most frequent elements are 1 and 2.
Example 2 — Single Element
$ Input: nums = [1], k = 1
Output: [1]
💡 Note: Only one element exists, so it's the most frequent by default.
Example 3 — Multiple Same Frequency
$ Input: nums = [1,2], k = 2
Output: [1,2]
💡 Note: Both elements appear once, so both are equally frequent. Return both in any order.

Constraints

  • 1 ≤ nums.length ≤ 105
  • k is in the range [1, number of unique elements in the array]
  • -104 ≤ nums[i] ≤ 104
  • Follow up: Your algorithm's time complexity must be better than O(n log n)

Visualization

Tap to expand
Top K Frequent Elements INPUT nums = [1,1,1,2,2,3] 1 1 1 2 2 3 k = 2 Count each element: 1: 3x 2: 2x 3: 1x Array length n = 6 Need top 2 frequent ALGORITHM STEPS 1 Build Frequency Map Count occurrences O(n) 2 Create Bucket Array Index = frequency Bucket: [] 0 [3] 1 [2] 2 [1] 3 3 Iterate from End High freq --> Low freq 4 Collect Top K Stop when k elements Bucket Sort Approach Time: O(n) Space: O(n) FINAL RESULT Scanning buckets from end: bucket[3] = [1] --> add 1 bucket[2] = [2] --> add 2 k=2 reached, STOP Output Array: [1, 2] OK - Correct! 1 appears 3 times 2 appears 2 times Key Insight: Bucket Sort achieves O(n) time by using frequency as array index. Since max frequency is n, we create n+1 buckets. This avoids O(n log n) sorting! Alternative: use Min-Heap of size k for O(n log k) time, which is also better than O(n log n) when k is much smaller than n. TutorialsPoint - Top K Frequent Elements | Optimal Solution (Bucket Sort)
Asked in
Google 65 Amazon 58 Facebook 42 Microsoft 38 Apple 25
286.3K Views
Very High Frequency
~25 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen