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 OverviewInput Array (k=2)111223Frequency Count1: 3 times2: 2 times3: 1 timeSelect Top K=212Most frequent elementsResult: [1, 2]
Understanding the Visualization
1
Input Array
Given array [1,1,1,2,2,3] and k=2
2
Count Frequencies
Element 1 appears 3 times, 2 appears 2 times, 3 appears 1 time
3
Select Top K
Return the 2 most frequent elements: [1,2]
Key Takeaway
🎯 Key Insight: Use bucket sort by frequency to achieve O(n) time complexity and avoid expensive sorting operations
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