Top K Frequent Elements
You are given an integer array and a number k. You need to return the k values that appear most often.
This is not asking for the elements in their original order, and it is not asking for their frequencies. The answer should be the actual values whose counts are highest. If nums = [1,1,1,2,2,3] and k = 2, the correct answer is [1,2] because 1 appears three times and 2 appears twice.
If the array is just [1] and k = 1, then the answer is simply [1].
So the task is to measure frequency first, then return the values belonging to the top k counts.
Example Input & Output
1 appears 3 times, 2 appears 2 times.
Only one element exists.
4 and 5 are the two most frequent values.
Algorithm Flow

Solution Approach
The natural first step is frequency counting with a hash map. Walk through the array and store how many times each value appears. After that pass, you know the exact frequency of every distinct number.
The second step is choosing the top k values. One straightforward way is to turn the frequency map into a list of [value, count] pairs, sort that list by count in descending order, and then take the first k values.
In outline, the process is:
1. Count each number with a map.
2. Convert the map into pairs like [num, count].
3. Sort those pairs so the largest counts come first.
4. Extract the first k numbers.
This is easy to understand because the map handles counting and the sorted pair list handles ranking.
Some versions of the problem can also be solved with buckets or a heap for better asymptotic performance, but the hash table plus sort approach is still a strong explanation-first solution. Its time complexity is usually O(n + m log m), where m is the number of distinct values, and the extra space is O(m).
Best Answers
import java.util.*;
class Solution {
public int[] top_k_frequent_elements(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int x : nums) freq.put(x, freq.getOrDefault(x, 0) + 1);
List<Map.Entry<Integer, Integer>> arr = new ArrayList<>(freq.entrySet());
arr.sort((a, b) -> b.getValue() - a.getValue());
int[] res = new int[k];
for (int i = 0; i < k; i++) res[i] = arr.get(i).getKey();
return res;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
