Start learning free

LESSON 85 OF 314 · HASH TABLE

Top K Frequent Elements in Scala: O(n) with Bucket Sort

Practice O(n) Read the full explanation

You get an array of integers nums and an integer k.

Return the k values that show up most often in nums, in any order.

How often a value shows up is its frequency. The tests always have one clear answer. Every value you return shows up more often than every value you leave out.

 

Example 1:

Input: nums = [5,3,5,8,3,5,2], k = 2
Output: [3,5]
Explanation: 5 shows up 3 times.
3 shows up twice.
8 and 2 show up once each.
The top 2 are 5 and 3. [5,3] is just as correct.

Example 2:

Input: nums = [9,9,9,9], k = 1
Output: [9]
Explanation: 9 is the only value.

Example 3:

Input: nums = [-2,6,-2,0,6,-2,6,1], k = 2
Output: [-2,6]
Explanation: -2 and 6 both show up 3 times.
0 and 1 show up once each.
A tie inside the answer is fine.
Only the values left out must show up less often.

 

Constraints:

  • 1 to 100,000 numbers.
  • Each number is from -10,000 to 10,000.
  • k is at least 1 and at most the number of different values in nums.
  • There is only one correct set of k values.

Note:

Your algorithm should run in O(n) time and use O(n) extra space, where n is the length of nums. Sorting the values by their frequency would already take O(n log n).

STEP 1 OF 12
    Ctrl + Enter to check

    SCALA · HASH TABLE

    Top K Frequent Elements in Scala, explained

    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

    1. 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.
    2. Loop over the values with for (num <- nums).
    3. Add one to the count. count(num) = count.getOrElse(num, 0) + 1. The getOrElse call gives 0 the first time a value shows up, where count(num) would throw an exception.
    4. Create the buckets. Array.fill(nums.length + 1)(mutable.ArrayBuffer[Int]()) makes nums.length + 1 separate empty buffers. The extra one is there because index nums.length must exist, for a value that fills the whole array.
    5. Loop over the entries of count with for ((num, freq) <- count). Looping over a map gives key and value pairs, and the pattern names both parts.
    6. Put each value in its bucket: buckets(freq) += num.
    7. Create result as an empty mutable.ArrayBuffer[Int].
    8. Start freq at nums.length in a var, the highest count any value could have. Most buckets are empty, which costs nothing but a step.
    9. Loop while result.length < k.
    10. Take a whole bucket: result ++= buckets(freq) adds every item of the buffer, where += would add one item.
    11. Move down: freq -= 1. The loop reads at most nums.length buckets, so it stays O(n).
    12. Return result.toArray. It converts the buffer to the Array[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 mutable prefix. HashMap and ArrayBuffer come from the package scala.collection.mutable. The code writes mutable.HashMap, which needs import scala.collection.mutable at the top of a standalone file. The default Map in 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 a NoSuchElementException with the message key not found: 5. That is why the counting uses getOrElse(num, 0). The alternative get(num) returns an Option.
    • 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.fill evaluates 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. The freq in for ((num, freq) <- count) exists only inside that loop. The later var freq is 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) with k = 1 gives [1]. There are two buckets, and bucket 1 holds the value.
    • Every value is the same. Array(3, 3, 3, 3) with k = 1 gives [3]. The value lands in the last bucket, index 4, which is why the array has nums.length + 1 buckets.
    • 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) with k = 3 gives [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 throws NoSuchElementException. Use getOrElse.
    • Making the array one slot short. With nums.length buckets, 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) with k = 2 gives [1,2].
    • Array(1) with k = 1 gives [1].
    • Array(4, -1, 4, -1, 7, 4, -1, 9) with k = 2 gives [-1,4], in whatever order the map produces.
    • Array(5, 5, 6, 6, 7) with k = 3 gives [5,6,7].
    • Array(3, 3, 3, 3) with k = 1 gives [3].
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free