Problem overview
The method topKFrequent receives an Array[Int] named nums and a number k, and returns 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 = Array(1, 1, 1, 2, 2, 3) and k = 2, the value 1 appears three times, 2 twice and 3 once, so the answer is [1,2]. For Array(4, -1, 4, -1, 7, 4, -1, 9) with k = 2, both 4 and -1 appear three times and 7 and 9 once; the call returns [-1,4], and [4,-1] would be just as correct.
Approach: count, then group by count
The first step is always counting: one pass over nums with a hash map from each value to its number of appearances. The question is how to pick the k biggest counts.
Sorting the distinct values by count works and costs O(n log n). The lesson aims for O(n), using one observation: a count can't be larger than nums.length, because a value can't appear more often than the array has elements. So the possible counts are the small range 1 to n, and the values can be dropped into buckets numbered by count. Bucket f holds the values that appear exactly f times. No comparisons between counts are needed: each value goes straight to its bucket.
Then read the buckets from the highest count down, collecting values until there are k of them. Because the answer is unique, the last bucket read never contains values that would overshoot k.
Step by step
- Create the counts.
val count = mutable.HashMap[Int, Int]()maps each value to how many times it was seen. Looking up a key takes constant time on average, so counting everything is one pass. - Loop over the values with
for (num <- nums). - Add one to the count.
count(num) = count.getOrElse(num, 0) + 1. ThegetOrElsecall gives 0 the first time a value shows up, wherecount(num)would throw an exception. - Create the buckets.
Array.fill(nums.length + 1)(mutable.ArrayBuffer[Int]())makesnums.length + 1separate empty buffers. The extra one is there because indexnums.lengthmust exist, for a value that fills the whole array. - Loop over the entries of
countwithfor ((num, freq) <- count). Looping over a map gives key and value pairs, and the pattern names both parts. - Put each value in its bucket:
buckets(freq) += num. - Create
resultas an emptymutable.ArrayBuffer[Int]. - Start
freqatnums.lengthin avar, the highest count any value could have. Most buckets are empty, which costs nothing but a step. - Loop while
result.length < k. - Take a whole bucket:
result ++= buckets(freq)adds every item of the buffer, where+=would add one item. - Move down:
freq -= 1. The loop reads at mostnums.lengthbuckets, so it staysO(n). - Return
result.toArray. It converts the buffer to theArray[Int]the method promises.
For Array(1, 1, 1, 2, 2, 3), the counts and the buckets look like this when printed:
HashMap(1 -> 3, 2 -> 2, 3 -> 1)
0:[] 1:[3] 2:[2] 3:[1] 4:[] 5:[] 6:[]
With k = 2, the loop reads bucket 6, 5 and 4 (all empty), then bucket 3 and bucket 2, and stops with [1,2].
The solution in Scala
class Solution {
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
val count = mutable.HashMap[Int, Int]()
for (num <- nums) {
count(num) = count.getOrElse(num, 0) + 1
}
val buckets = Array.fill(nums.length + 1)(mutable.ArrayBuffer[Int]())
for ((num, freq) <- count) {
buckets(freq) += num
}
val result = mutable.ArrayBuffer[Int]()
var freq = nums.length
while (result.length < k) {
result ++= buckets(freq)
freq -= 1
}
result.toArray
}
}
Scala details worth knowing:
- The
mutableprefix.HashMapandArrayBuffercome from the packagescala.collection.mutable. The code writesmutable.HashMap, which needsimport scala.collection.mutableat the top of a standalone file. The defaultMapin Scala is immutable, so the mutable version is needed for counting in place. map(key)throws for a missing key. On an empty map,m(5)throws aNoSuchElementExceptionwith the messagekey not found: 5. That is why the counting usesgetOrElse(num, 0). The alternativeget(num)returns anOption.count(num) = ...inserts or updates. On a mutable map, assigning to a key adds it when it's missing and replaces the value when it exists.Array.fillevaluates its expression for every slot. That gives each bucket its own buffer. Creating one buffer first and filling the array with that name would put the same buffer in every slot: adding one value to bucket 0 would then make all of the buckets look the same size.- Two variables named
freq. Thefreqinfor ((num, freq) <- count)exists only inside that loop. The latervar freqis a separate variable, declared after it. - Iteration order of a hash map is unspecified. That is why the problem allows the answer in any order. In the 4, -1 example, the result printed is
[-1,4].
Complexity
Time: O(n), where n is nums.length. Counting is one pass. Filling the buckets visits each distinct value once. Creating the buckets takes n + 1 steps, and reading them takes at most n steps plus the total size of the buckets read, which is at most the number of distinct values. A sort by count would add a factor of log n.
Space: O(n). The map holds one entry per distinct value, there are n + 1 buckets, and the result has k values. All of these are at most proportional to n.
Edge cases and common mistakes
- One element.
Array(1)withk = 1gives[1]. There are two buckets, and bucket 1 holds the value. - Every value is the same.
Array(3, 3, 3, 3)withk = 1gives[3]. The value lands in the last bucket, index 4, which is why the array hasnums.length + 1buckets. - Negative values. They work as map keys without any special handling. Only the counts are used as array indices, and counts are never negative.
- A bucket with several values.
Array(5, 5, 6, 6, 7)withk = 3gives[5,6,7]: bucket 2 supplies two values and bucket 1 the third. The answer is unique here, because no value is left out at the cut. - Using
count(num)for the first occurrence. It throwsNoSuchElementException. UsegetOrElse. - Making the array one slot short. With
nums.lengthbuckets, the highest possible index,nums.length, doesn't exist. The code would fail on an array whose values are all equal. - Reading buckets from index 0 up. That collects the least frequent values.
- Sorting by count. It gives correct answers, but at
O(n log n)it misses the lesson's bound.
Testing
Array(1, 1, 1, 2, 2, 3)withk = 2gives[1,2].Array(1)withk = 1gives[1].Array(4, -1, 4, -1, 7, 4, -1, 9)withk = 2gives[-1,4], in whatever order the map produces.Array(5, 5, 6, 6, 7)withk = 3gives[5,6,7].Array(3, 3, 3, 3)withk = 1gives[3].
