Start learning free

LESSON 85 OF 314 · HASH TABLE

Top K Frequent Elements in Kotlin: O(n) with a HashMap and Buckets

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

    KOTLIN · HASH TABLE

    Top K Frequent Elements in Kotlin, explained

    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

    1. 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.
    2. Visit every value with for (num in nums).
    3. Add one to the value's count: count[num] = count.getOrDefault(num, 0) + 1. For a value seen for the first time, getOrDefault gives 0.
    4. Create the buckets. Array(nums.size + 1) { mutableListOf<Int>() } makes an array with indices 0 to nums.size, since a count can reach nums.size. The lambda runs once per index, so each bucket is its own empty list.
    5. Visit every map entry with for ((num, freq) in count), which splits each entry into its key and value.
    6. Fill the buckets: buckets[freq].add(num) puts each value in the place for its count, without comparing counts with each other.
    7. Prepare the answer as an empty mutableListOf<Int>() named result.
    8. 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.
    9. Loop while (result.size < k).
    10. Collect a bucket: result.addAll(buckets[freq]) adds every item of the bucket, where add adds only one. Because the answer is unique, a bucket never pushes result past k values.
    11. Move down with freq--.
    12. Return result.toIntArray(), since the function returns an IntArray.

    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] returns null when 9 is not a key, so its type is Int?. Writing count[num] = count[num] + 1 doesn't compile: the compiler reports that an operator call is prohibited on a nullable receiver of type Int?. getOrDefault(num, 0) returns a plain Int. The idiom (count[num] ?: 0) + 1 works too.
    • One list per bucket. Array(n) { ... } runs the lambda for every index, so each element is a new list. Reusing one list, as in val same = mutableListOf<Int>() and Array(3) { same }, makes all three slots the same list: after bad[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 variable freq exists only inside that loop, so the var freq declared later is a separate variable.
    • toIntArray() converts a List<Int> to a primitive IntArray.
    • 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] with k = 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.size times, so the array needs nums.size + 1 slots, with the extra one for index nums.size.
    • k equal to the number of distinct values. For [3, 1, 2] with k = 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]
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free