Problem overview
The method topKFrequent receives an int[] nums and an integer k, and returns an int[] with the k values that appear most often in nums, in any order. The frequency of a value is how many times it appears. The answer is guaranteed to be unique: every value in it appears more times than every value left out.
For nums = [1, 1, 1, 2, 2, 3] and k = 2, the value 1 appears 3 times, 2 appears twice and 3 once, so the answer is [1, 2]. For [4, -1, 4, -1, 7, 4, -1, 9] with k = 2, the values 4 and -1 appear 3 times each and 7 and 9 once, so the answer is [-1, 4] or [4, -1].
Approach: count, then bucket by count
The first half is the same in every solution: count each value in a hash map, in one pass. After that, the straightforward move is to sort the distinct values by count and take the first k. That costs O(n log n), and the lesson wants O(n).
The way around it is to notice that a count is a whole number between 1 and nums.length. So instead of comparing counts, give every possible count its own bucket, a list of the values that appear exactly that many times, and drop each value straight into the bucket for its count. That is a bucket sort. Then read the buckets from the highest count down, collecting values until you have k of them.
For [1, 1, 1, 2, 2, 3] the counts are {1=3, 2=2, 3=1}. With 6 elements there are buckets 0 to 6, and the filled ones are bucket 1 holding 3, bucket 2 holding 2 and bucket 3 holding 1. Reading from bucket 6 down, the first non-empty bucket is 3, which gives 1, and the next is 2, which gives 2. With k = 2 the answer is [1, 2].
In Java terms, after the values are distributed, the buckets list is [[], [3], [2], [1], [], [], []].
Step by step
- Create the map.
Map<Integer, Integer> count = new HashMap<>()maps each value to the number of times it appears. - Loop over
numswith a for-each loop,for (int num : nums). - Add one to the value's count with
count.put(num, count.getOrDefault(num, 0) + 1). For a value seen for the first time,getOrDefaultgives 0, wheregetwould givenull. - Create
bucketsas aList<List<Integer>>.buckets.get(f)will hold the values that appear exactlyftimes. - Fill it with empty lists. Loop
ifrom 0 whilei <= nums.lengthandadd(new ArrayList<>())each time. Counts run from 1 tonums.length, so indices 0 tonums.lengthneednums.length + 1buckets. Each bucket needs its own list, so every pass creates a new one. - Distribute the values. For each key
numincount.keySet(), add it to the bucket at indexcount.get(num). - Prepare the answer. Create
result, aList<Integer>, and anint freqstarting atnums.length, the highest possible count. - Collect from the top. While
result.size() < k, callresult.addAll(buckets.get(freq))and thenfreq--. Empty buckets add nothing. The loop visits at mostnums.lengthbuckets, so it stays O(n). - Convert to an array.
result.stream().mapToInt(i -> i).toArray()turns the list ofIntegerinto anint[].
The solution in Java
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int num : nums) {
count.put(num, count.getOrDefault(num, 0) + 1);
}
List<List<Integer>> buckets = new ArrayList<>();
for (int i = 0; i <= nums.length; i++) {
buckets.add(new ArrayList<>());
}
for (int num : count.keySet()) {
buckets.get(count.get(num)).add(num);
}
List<Integer> result = new ArrayList<>();
int freq = nums.length;
while (result.size() < k) {
result.addAll(buckets.get(freq));
freq--;
}
return result.stream().mapToInt(i -> i).toArray();
}
}
The Java details worth a closer look:
HashMap.getreturnsnullfor a missing key. Unboxing thatnullinto anintthrowsNullPointerException.getOrDefault(num, 0)avoids it. Herecount.get(num)is safe becausenumcomes fromcount.keySet().- Boxing and unboxing. Generic collections hold
Integerobjects, notint. The compiler converts automatically infor (int num : count.keySet())and inbuckets.get(count.get(num)), where anIntegerbecomes theintindex. - Why
addAll.add(list)would put the whole bucket intoresultas one element, which does not compile for aList<Integer>.addAlladds each element. new ArrayList<>()in a loop. Adding the same list objectnums.length + 1times would make every bucket the same bucket. The loop body creates a new list per pass.- The stream conversion.
mapToInt(i -> i)unboxes eachIntegerto anint, andtoArray()then builds anint[]. A plainresult.toArray()would give anObject[], which is not what the method returns. - Order of the answer. A
HashMapdoes not promise an iteration order, so values in the same bucket can come out in either order. The statement accepts any order. On the second example the code returns[-1, 4].
Complexity
Time: O(n). Counting is one pass over nums. Building the buckets takes nums.length + 1 steps. Distributing the values takes one step per distinct value, and there are at most n of them. Collecting visits at most nums.length buckets and adds each value at most once.
Space: O(n). The map holds at most n entries, there are nums.length + 1 buckets, and the buckets together hold each distinct value once.
Edge cases and common mistakes
- One element.
[1]withk = 1gives[1]. There are two buckets, and bucket 1 holds the value. - One distinct value.
[5, 5, 5, 5]withk = 1gives[5]. It sits in bucket 4, which is the first one read. - Negative values. Values are map keys, never indices, so negatives like -1 need no special care. Only the counts index the buckets.
- Too few buckets. Creating
nums.lengthbuckets instead ofnums.length + 1breaks when a single value fills the array: its count equalsnums.length, and that index would not exist. - Ties at the cut. The statement guarantees none. If the guarantee did not hold, for example
k = 3on the second example, where three values are needed but two share the last place, a whole bucket would be added and the result would have 4 values:[-1, 4, 7, 9]. This lesson's tests never ask for such a case. - Sorting by count instead. It works, but it is O(n log n). The bucket idea works because a count has a small, known range.
Testing
nums = [1, 1, 1, 2, 2, 3],k = 2gives[1, 2].nums = [1],k = 1gives[1].nums = [4, -1, 4, -1, 7, 4, -1, 9],k = 2gives[-1, 4], which is the same set as[4, -1].nums = [5, 5, 5, 5],k = 1gives[5].
