📚 PracticeMediumAlgorithm ProblemCoding Ready

Top K Frequent Elements

arrayhash-tableheapbucket-sort
LeetCode #347
Updated Dec 20, 2025

Question

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

LeetCode: Top K Frequent Elements

Example:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Input: nums = [1], k = 1
Output: [1]

Note: You may assume k is always valid (1 ≤ k ≤ number of unique elements).

Hints

Hint 1

First, count the frequency of each element. What data structure is good for counting?

Hint 2

Once you have frequencies, you need the top k. Think about using a heap - do you want min heap or max heap?

Hint 3

There's an O(n) solution using bucket sort! Can you group elements by their frequency?


Your Solution

python
Auto-saves every 30s

Try solving the problem first before viewing the solution


0:00time spent