Skip to main content

Top K Frequent Elements - Solution & Explanation

MediumArrayHash TableDivide and ConquerSorting17 min readAsked at: Amazon, Microsoft, Apple +50
Practice this problem

Problem Statement

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

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

 

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

Approach Overview

Problem Overview: You receive an integer array and an integer k. The task is to return the k most frequent elements in the array. Order does not matter, but the algorithm must be efficient since the input size can be large.

Frequency problems usually start with counting occurrences. The main challenge is extracting the top k elements efficiently without sorting the entire dataset. Two common strategies are a heap-based approach and bucket sort.

Approach 1: Hash Map + Min-Heap (O(n log k) time, O(n) space)

First count how many times each number appears using a hash table. This converts the original array problem into a frequency lookup like {number -> count}. Next, maintain a min-heap of size k using a priority queue. Iterate through the frequency map and push (frequency, value) pairs into the heap. Whenever the heap size exceeds k, remove the smallest frequency element. This keeps only the top k frequent elements in the heap. The complexity is O(n log k) because each heap insertion or removal costs log k, and you perform it for up to n unique elements.

Approach 2: Bucket Sort (O(n) time, O(n) space)

Bucket sort removes the need for a heap entirely. Start by counting frequencies using a hash map. The maximum frequency of any number cannot exceed n, so create an array of buckets where the index represents frequency. Each bucket stores the numbers that appear that many times. After building the buckets, iterate from the highest frequency bucket downwards and collect numbers until you gather k elements. This works because frequencies map directly to indices. The approach runs in O(n) time since both counting and bucket traversal are linear.

Approach 3: Quickselect on Frequencies (Average O(n) time, O(n) space)

Another strategy is applying Quickselect, similar to finding the kth largest element. Build a frequency map, convert it into a list of pairs, and partition the list based on frequency. Each partition step moves higher-frequency elements toward the front until the top k region is identified. Average complexity is O(n), though worst-case becomes O(n²). This approach avoids extra structures like heaps or buckets but is more complex to implement correctly.

Recommended for interviews: The hash map + heap solution is the most commonly expected approach. It demonstrates clear understanding of counting with a array traversal and efficient top-k extraction using a priority queue. Bucket sort is even faster at O(n), and strong candidates often mention it as the optimal solution when frequency bounds allow it.

Approach 1: Using a Hash Map and Min-Heap

This approach uses a hash map to count the frequency of each element. We then use a min-heap to keep track of the top k elements.

We use a frequency map to track occurrences of each number. Then, we create a struct array for frequencies, sort it, and return the top k elements.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for storing frequencies.

Try this approach in the editor →

Approach 2: Using Bucket Sort

This approach involves using bucket sort where we create buckets for frequency counts and then extract the top k frequent elements.

We manually record each element's frequency and sort the list based on counts into a frequency bucket. Then, we retrieve the top k elements.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n + k).
Space Complexity: O(n).

Try this approach in the editor →

Approach 3: Hash Table + Priority Queue (Min Heap)

We can use a hash table cnt to count the occurrence of each element, and then use a min heap (priority queue) to store the top k frequent elements.

First, we traverse the array once to count the occurrence of each element. Then, we iterate through the hash table, storing each element and its count into the min heap. If the size of the min heap exceeds k, we pop the top element of the heap to ensure the heap size is always k.

Finally, we pop the elements from the min heap one by one and place them into the result array.

The time complexity is O(n log k), and the space complexity is O(k). Here, n is the length of the array.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using a Hash Map and Min-Heap

Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for storing frequencies.

Using Bucket Sort

Time Complexity: O(n + k).
Space Complexity: O(n).

Hash Table + Priority Queue (Min Heap)—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Hash Map + Min-HeapO(n log k)O(n)General solution when you need top-k elements efficiently without sorting everything
Bucket SortO(n)O(n)Best when frequency range is bounded by n and you want linear time
QuickselectAverage O(n), worst O(n²)O(n)Useful when avoiding heaps and implementing selection algorithms

Video Solution

Top K Frequent Elements - Bucket Sort - Leetcode 347 - Python • NeetCode • 938,789 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Top K Frequent Elements easy or hard?
Top K Frequent Elements is generally rated Medium on coding platforms. The counting step is straightforward, but selecting the top k efficiently requires knowledge of heaps, bucket sort, or selection algorithms.
Top K Frequent Elements Python/Java solution
Typical Python and Java solutions first build a frequency dictionary or HashMap. Then they either push elements into a priority queue of size k or place them into frequency buckets. Both implementations are concise and usually run in O(n log k) or O(n) depending on the chosen strategy.
How to solve Top K Frequent Elements in O(n)?
Use bucket sort after counting frequencies with a hash map. Create an array of buckets where the index represents frequency, and place numbers into the bucket matching their count. Traverse the buckets from highest frequency downward and collect elements until k numbers are returned. Both counting and traversal are linear, giving O(n) time complexity.
What is the best approach for Top K Frequent Elements?
The most practical approach uses a hash map to count frequencies and a min-heap of size k to track the most frequent elements. This runs in O(n log k) time and O(n) space. Many interviewers accept this as the standard solution because it is easy to implement and scales well when k is much smaller than n.
Is Top K Frequent Elements asked at Google/Amazon/Meta?
Top K Frequent Elements is a common interview problem at companies like Amazon, Google, Meta, and Microsoft. It tests knowledge of hash tables, heaps, and frequency counting patterns, which appear frequently in real system tasks such as log analysis or ranking systems.
What data structure is used in Top K Frequent Elements?
The core data structure is a hash map for counting frequencies. Many solutions combine it with a min-heap (priority queue) to maintain the top k elements efficiently. Alternative approaches use bucket arrays or Quickselect to avoid heap operations.
What is the time complexity of Top K Frequent Elements?
The common heap-based solution runs in O(n log k) time because each frequency entry may be inserted into a heap of size k. A bucket sort optimization reduces the complexity to O(n) time by grouping numbers by frequency and scanning buckets from highest to lowest.

Ready to solve this problem?

Practice Top K Frequent Elements with our built-in code editor and test cases.

Practice on FleetCode