Problem overview
The function topKFrequent receives an IntArray named nums and an integer k, and returns the k values that appear most often in nums, in any order. A value's frequency is the number of times it appears. The answer is guaranteed to be unique: every value in it appears more often than every value left out, so there is never a tie at the cut.
For nums = [1, 1, 1, 2, 2, 3] and k = 2, the value 1 appears three times, 2 appears twice and 3 once, so the answer is [1, 2]. For [4, -1, 4, -1, 7, 4, -1, 9] and k = 2, the values 4 and -1 appear three times each and the others once, so the answer holds 4 and -1 in either order.
Approach
The direct plan is to count the occurrences of each value, sort the distinct values by count, and take the first k. Sorting costs O(n log n), and the task asks for O(n).
The key observation is that a count can't be larger than nums.size. So instead of comparing counts, put each value straight into a bucket for its count: buckets[f] holds the values that appear exactly f times. This is a bucket sort. The most frequent values then sit in the buckets with the highest indices, so reading the buckets from the top down and stopping once k values are collected gives the answer. The whole thing is three linear steps: count, bucket, collect.
Step by step
- Count. Create
val count = HashMap<Int, Int>(), mapping each value to the number of times it appears. A hash table finds a key in constant time, so counting is one pass. - Visit every value with
for (num in nums). - Add one to the value's count:
count[num] = count.getOrDefault(num, 0) + 1. For a value seen for the first time,getOrDefaultgives 0. - Create the buckets.
Array(nums.size + 1) { mutableListOf<Int>() }makes an array with indices 0 tonums.size, since a count can reachnums.size. The lambda runs once per index, so each bucket is its own empty list. - Visit every map entry with
for ((num, freq) in count), which splits each entry into its key and value. - Fill the buckets:
buckets[freq].add(num)puts each value in the place for its count, without comparing counts with each other. - Prepare the answer as an empty
mutableListOf<Int>()namedresult. - Start at the top.
var freq = nums.size, the highest count any value can have. Empty buckets add nothing, so walking down from the top is safe. - Loop
while (result.size < k). - Collect a bucket:
result.addAll(buckets[freq])adds every item of the bucket, whereaddadds only one. Because the answer is unique, a bucket never pushesresultpastkvalues. - Move down with
freq--. - Return
result.toIntArray(), since the function returns anIntArray.
For [1, 1, 1, 2, 2, 3], count prints as {1=3, 2=2, 3=1} and the buckets, from index 0 to 6, hold [[], [3], [2], [1], [], [], []]. Starting at index 6 and walking down, the loop finds 1 at index 3 and 2 at index 2, and with k = 2 it stops.
The solution in Kotlin
class Solution {
fun topKFrequent(nums: IntArray, k: Int): IntArray {
val count = HashMap<Int, Int>()
for (num in nums) {
count[num] = count.getOrDefault(num, 0) + 1
}
val buckets = Array(nums.size + 1) { mutableListOf<Int>() }
for ((num, freq) in count) {
buckets[freq].add(num)
}
val result = mutableListOf<Int>()
var freq = nums.size
while (result.size < k) {
result.addAll(buckets[freq])
freq--
}
return result.toIntArray()
}
}
Kotlin details worth knowing:
- Reading a missing key.
count[9]returnsnullwhen 9 is not a key, so its type isInt?. Writingcount[num] = count[num] + 1doesn't compile: the compiler reports that an operator call is prohibited on a nullable receiver of typeInt?.getOrDefault(num, 0)returns a plainInt. The idiom(count[num] ?: 0) + 1works too. - One list per bucket.
Array(n) { ... }runs the lambda for every index, so each element is a new list. Reusing one list, as inval same = mutableListOf<Int>()andArray(3) { same }, makes all three slots the same list: afterbad[0].add(1)the array shows[[1], [1], [1]]. - Destructuring.
for ((num, freq) in count)unpacks each map entry into its key and value. The loop variablefreqexists only inside that loop, so thevar freqdeclared later is a separate variable. toIntArray()converts aList<Int>to a primitiveIntArray.- Order is free. The solution returns
[-1, 4]for the third example, which is as correct as[4, -1], since the order doesn't matter.
Complexity
Time is O(n): one pass to count, one pass over at most n distinct values to fill the buckets, and a walk over at most nums.size buckets. Space is O(n): the map, the buckets and the result together hold at most a few entries per value.
Edge cases and common mistakes
- A single value. For
[1]withk = 1, the buckets array has two slots, the value lands in bucket 1, and the loop returns[1]. - Buckets sized to the number of distinct values. A value can appear
nums.sizetimes, so the array needsnums.size + 1slots, with the extra one for indexnums.size. kequal to the number of distinct values. For[3, 1, 2]withk = 3, every value is returned: the solution gives[1, 2, 3].- Negative values. They are fine as map keys. Only the counts index the array, and counts are never negative.
- Sorting the entries by count. It works and is a good first version, but it costs O(n log n).
Testing
Results the solution returns:
[1, 1, 1, 2, 2, 3], k = 2 -> [1, 2]
[1], k = 1 -> [1]
[4, -1, 4, -1, 7, 4, -1, 9], k = 2 -> [-1, 4]
[5, 5, 6, 6, 6, 7], k = 1 -> [6]
[3, 1, 2], k = 3 -> [1, 2, 3]
