intermediate7 min read·Updated September 18, 2026
Top K Frequent Elements Explained: Finding Top 2 in [1, 1, 1, 2, 2, 3]
Master Top K frequent elements with a step-by-step walkthrough of finding the top 2 in [1, 1, 1, 2, 2, 3]. Learn mental models, bucket sort, and edge cases.
By Learnisim AI·Published September 18, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
- Hash maps and frequency counting
- Basic array manipulation
- Understanding of $O(N)$ time complexity
Why
Why We Need a Smarter Way to Find Top Frequent Elements
Phase 1: The Raw Frequency Problem
Imagine you are handed an inventory log of items that scan repeatedly, and you need to surface the most popular ones instantly. Consider our working example: given
nums = [1, 1, 1, 2, 2, 3] and , our goal is to return the values with the highest frequency, which is [1, 2] because 1 appears three times and 2 appears twice.If you approach this without a structured plan, your first instinct might be to sort the entire collection by how often each element appears. But sorting a massive dataset just to pluck off the top two elements wastes precious computational cycles on ordering elements you do not even care about. As datasets grow, waiting for a full sort becomes a severe bottleneck.
We need a way to track counts efficiently and isolate only the top items without paying the heavy tax of a full sort. Understanding how to handle this efficiently is what the Top K frequent elements pattern is all about.
Model
Mental Model: Frequencies, Buckets, and the $k$ Threshold
Phase 2: Mapping Values to Counts
When we look at our working example, and , we are not just searching for raw values. We are building a two-tier relationship: first from element to frequency, and then from frequency back to elements.
In our frequency map, the raw elements map directly to their tally:
•Value 1 appears 3 times
•Value 2 appears 2 times
•Value 3 appears 1 time
To find the top 2 frequent elements, our mental model shifts from looking at the numbers themselves to looking at their frequency buckets. Imagine an array of empty buckets where the index represents how many times an element appeared. Element 3 falls into bucket
3. By inspecting these buckets from the highest frequency down to the lowest, we can easily collect our target of items without sorting every single pair.
1.Element 2 falls into bucket
2.Element 1 falls into bucket
3. By inspecting these buckets from the highest frequency down to the lowest, we can easily collect our target of items without sorting every single pair.
Worked example
Tracing Frequency Counts and Bucket Collection Step by Step
Phase 3: Worked example
Let us trace our locked example from start to finish using the bucket sort approach. We start with our Given: and . Our goal is to return the two values with the highest frequency.
Given
--
- Length
Steps
1. Build the frequency map: Count how many times each element appears in .-
-
-
2.Initialize the bucket array: Create an array of empty lists or buckets where the index represents the frequency, ranging from index 0 to 6.
- (indices 0 to 6)
3.Distribute elements into buckets: Place each unique element into the bucket matching its frequency count.
- Bucket 1: (since element 3 appears 1 time)
- Bucket 2: (since element 2 appears 2 times)
- Bucket 3: (since element 1 appears 3 times)
4. Collect from highest bucket down: Scan from right to left (index 6 down to 0) and append elements to our result list until we reach size .
•Index 6: empty
•Index 5: empty
•Index 4: empty
- Index 3: contains . Result becomes . Length is .
- Index 2: contains . Result becomes . Length is , so we stop.
Result
- (or depending on inner order).Based on this exact trace, what would be the intermediate bucket state if we changed instead of 2?
Try this: Given nums = [1, 1, 1, 2, 2, 3] and k = 1, trace which bucket will supply the final result and list the elements collected.
Practice
Practice: Tracing Buckets and Frequencies on a Shifted Array
Phase 4: Practice
Now that you have traced the frequency map and bucket collection for with , it is time to test your mental model on a slightly modified variant. Changing the distribution of elements shifts which bucket indices populate, but the underlying frequency-to-bucket mechanics remain identical.
Work through the prompt below using pencil and paper. Map out the exact frequency counts first, build your bucket array mentally or on scratch paper, and collect the top elements from right to left.
Apply
Apply
Phase 5: Transfer
Now that you have mastered tracking frequencies and scanning buckets for the working example , you can apply this exact structural pattern to new domains. The core trick—mapping items to their raw frequencies first, then indexing them by frequency buckets rather than sorting the entire dataset—appears anywhere you need real-time analytics without the tax.
Imagine you are building a log analysis dashboard for an API gateway. Instead of integers, your input is a stream of IP addresses making requests over a minute. You need to flag the top most active IPs for rate-limiting review. Just as you built a frequency map for our integers, you build a frequency map of IP strings. You then route those IPs into frequency buckets where the bucket index represents the request count. Scanning from the highest bucket down immediately surfaces your top abusers.
This transfer works because frequency counting and bucket sorting are agnostic to data types. Whether your elements are numbers, strings, or database record IDs, the bottleneck is always counting. Once counts are known, bucket sorting bypasses comparison sorting entirely by leveraging the maximum possible frequency as a finite array boundary.
FAQ
How do we find the top 2 frequent elements in [1, 1, 1, 2, 2, 3]?
First, count frequencies: 1 appears 3 times, 2 appears 2 times, and 3 appears 1 time. Using a bucket sort approach where the index represents frequency, elements are placed into buckets corresponding to their counts. Scanning backwards from the highest frequency bucket gives us [1, 2] for k = 2.
Why use bucket sort instead of a heap for Top K frequent elements?
While a min-heap gives time complexity, bucket sort achieves time complexity by using the maximum possible frequency (which is bounded by the array length ) as the index for our buckets.
What is the time and space complexity of the bucket sort approach?
Both the time and space complexity are , where is the number of elements in the array. We iterate through the array to build the frequency map and populate buckets, then collect the results in linear time.
How do we handle elements with the same frequency?
If multiple elements share the same frequency and fit within the remaining quota, bucket sort naturally groups them together. Depending on problem constraints, any valid subset of those elements that satisfies is usually accepted.