Crash Code Part-5 (Top K Elements!)
Trying to solve old coding questions, because reasons: The Frequency Counter and Sort
776 Words — Reading Time: 3 Minutes, 31 Seconds
23 July 2026, 6:30:00 PM
Problem Description
You are given a list of integers nums. Your task is to find the k elements that occur most frequently in the list. Return exactly k integers sorted in ascending order.
The catch? We want to do this efficiently without relying on overly complex nested loops, leveraging Java 8’s powerful Collections framework and lambda expressions instead. Everything needs to happen cleanly inside the main method.
Constraints
- 1 <= n <= 10000
- -1000 <= nums[i] <= 1000
- 1 <= k <= n
Input
- The first line contains an integer
n, the number of elements in the list. - The next
nlines each contain an integer representing the elements ofnums. - The last line contains an integer
k.
Output
Return the k most frequent elements as a List<Integer>, sorted in ascending order. (Note: the driver code handles printing).
Examples
Example
Input:
6
1
2
2
3
3
3
2
Output:
2
3
Explanation:
n = 6, meaning there are 6 elements in the list.
The list nums is: [1, 2, 2, 3, 3, 3].
k = 2, meaning we need the 2 most frequent numbers.
Now, count the frequency of each number:
* 1 -> occurs 1 time
* 2 -> occurs 2 times
* 3 -> occurs 3 times
The top 2 elements with the highest frequency are 3 (3 times) and 2 (2 times).
After sorting them in ascending order, we get:
[2, 3].
The Concepts Under the Hood
Instead of manually counting and tracking highest counts with multiple nested arrays (which gets messy and scales poorly), we can use a combination of a Hash Map and Custom Sorting. It relies on a neat logical trick using simple steps to achieve a clean solution:
- The Hash Map Math: We iterate through the array once and store the frequency of each number using a Hash Map (
Map<Integer, Integer>). We utilize Java 8’sgetOrDefaultto seamlessly initialize or increment our frequency counts. - Isolate Unique Elements: We grab only the unique keys (the distinct numbers) from our map and place them into a new list.
- Custom Sort by Frequency: We sort this list of unique numbers. Instead of sorting by their natural value, we provide a custom Java 8 lambda comparator to sort them based on their frequency (the values from our map) in descending order.
- Sublist and Final Sort: We slice out the first
kelements from our newly sorted list, which represent our top frequent numbers. Finally, because the constraints strictly dictate an ascending output, we sort this specific sublist one last time in natural ascending order.
Visualizing the Frequency Map and Sort
Since we want to rely on standard Java utilities rather than external helper methods, we execute a custom comparator sort directly inline. Here is how the mapping and sorting technique looks in action for the list [1, 2, 2, 3, 3, 3].
Step 1: Building the Map
We process each number, mapping the element (Key) to its occurrence count (Value).
Number (Key) -> Frequency (Value)
1 -> 1
2 -> 2
3 -> 3
Step 2: Extract Keys and Custom Sort
We pull the unique keys into a list: [1, 2, 3].
Next, we sort this list by comparing the Values from the map, pushing the highest frequencies to the front.
- Compare 1 and 2: freq(2) is 2, freq(1) is 1. Number 2 moves ahead.
- Compare 2 and 3: freq(3) is 3, freq(2) is 2. Number 3 moves ahead.
Sorted Unique List:
[ 3, 2, 1 ]
Step 3: Extract Top K and Final Sort
We need k = 2 elements, so we take a sublist from index 0 to 2.
Sublist: [3, 2]
We perform a final ascending sort to satisfy the output requirements:
Final Output: [2, 3]
Solve
| |