Start learning free

LESSON 369 OF 673 · HASH TABLE

Top K Frequent Elements in Python: O(n) Counting and Bucket Sort

Practice O(n) Read the full explanation

You get a list 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

    PYTHON · HASH TABLE

    Top K Frequent Elements in Python, explained

    Problem overview

    The method topKFrequent receives a list of integers, nums, and an integer k. It returns the k values that appear most often in nums, in any order. The frequency of a value is the number of times it appears, and 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 answer is [1, 2]: 1 appears 3 times, 2 appears twice and 3 once. In [4, -1, 4, -1, 7, 4, -1, 9] with k = 2, the values 4 and -1 each appear 3 times and the others once, so [4, -1] and [-1, 4] are both correct. The lesson asks for O(n) time and O(n) extra space.

    Approach: count, then bucket by frequency

    The first half is the same for any solution: count how many times each value appears, with a dictionary that maps each value to its count. That is one pass over the list, since a dictionary finds a key in constant time on average.

    The second half is choosing the k largest counts. Sorting the values by count costs O(n log n). A faster way uses one fact: a count can't be larger than len(nums). So make a list of buckets, one for each possible count, and put each value in the bucket for its count. This is a bucket sort: every value goes straight to its place, with no comparisons between counts.

    The most frequent values then sit in the buckets with the highest indices. Start at the top bucket, len(nums), and walk down, collecting values until there are k of them. The walk visits at most len(nums) buckets, so the whole method stays O(n).

    On [1, 1, 1, 2, 2, 3] the counts are {1: 3, 2: 2, 3: 1}. The list has 6 elements, so there are 7 buckets, and after filling them they are [[], [3], [2], [1], [], [], []]. Bucket 3 holds the value 1, bucket 2 holds 2 and bucket 1 holds 3. Walking down from bucket 6 collects 1 and then 2, and the method returns [1, 2].

    Step by step

    1. Create an empty dictionary named count. It maps each value to the number of times it appears.
    2. Loop over every num in nums.
    3. Add one to its count: count[num] = count.get(num, 0) + 1. The get with a default of 0 handles a value seen for the first time.
    4. Create the buckets with a list comprehension, [[] for _ in range(len(nums) + 1)]. Counts run from 1 to len(nums), so index len(nums) must exist, hence the + 1. buckets[f] will hold the values that appear exactly f times.
    5. Loop over count.items(), unpacking each pair into num and freq.
    6. Append num to buckets[freq].
    7. Create an empty result for the answer.
    8. Start freq at len(nums), the highest count a value can have. It is not known which buckets are full, so the walk starts at the top.
    9. Loop while len(result) < k.
    10. Add the whole bucket to result with extend. Because the answer is unique, a bucket never holds more values than are still needed. A bucket that pushed result past k would mean a tie at the cut.
    11. Move down to the next count: freq -= 1.
    12. Return result.

    The solution in Python

    class Solution:
        def topKFrequent(self, nums: List[int], k: int) -> List[int]:
            count = {}
            for num in nums:
                count[num] = count.get(num, 0) + 1
            buckets = [[] for _ in range(len(nums) + 1)]
            for num, freq in count.items():
                buckets[freq].append(num)
            result = []
            freq = len(nums)
            while len(result) < k:
                result.extend(buckets[freq])
                freq -= 1
            return result
    

    The Python details that matter here:

    • count.get(num, 0) returns 0 for a missing key. Writing count[num] += 1 for a new value raises a KeyError.
    • The list comprehension builds separate lists. It evaluates [] once per item. The shortcut [[]] * n repeats one list n times, so appending to one bucket would appear in all of them: appending 1 to the first of [[]] * 3 gives [[1], [1], [1]].
    • _ as a loop variable is a convention for a value that is not used.
    • extend versus append. extend adds each item of a list. append would add the whole bucket as one nested list.
    • count.items() yields the key-value pairs, which the for loop unpacks directly.
    • Reusing freq. The loop variable of the second for and the later counter share a name. That is fine, because the first loop is finished by then and freq is assigned afresh.

    The standard library offers shorter ways, such as collections.Counter(nums).most_common(k), but that sorts by count and is O(n log n). The buckets are what keep this version linear.

    Complexity

    Time: O(n). Counting is one pass. Filling the buckets visits each distinct value once, and there are at most n of them. The walk down the buckets visits at most n + 1 of them, and the values it collects add up to k.

    Space: O(n). The dictionary holds up to n distinct values, and the bucket list has n + 1 entries. Every value is stored in exactly one bucket.

    Edge cases and common mistakes

    • A single value. [1] with k = 1 gives [1]. There are 2 buckets, and the walk starts at bucket 1.
    • k equals the number of distinct values. [1, 2, 3] with k = 3 gives [1, 2, 3]. The walk empties every bucket down to count 1.
    • Negative values. They are ordinary dictionary keys. The buckets are indexed by count, never by the value, so a value like -1 causes no trouble.
    • Ties below the cut. Values with equal counts share a bucket. The guarantee that the answer is unique means any tie is entirely inside the answer or entirely outside it, so the whole-bucket extend never overshoots k.
    • Bucket list too short. Using len(nums) buckets instead of len(nums) + 1 fails when one value fills the list, because the count len(nums) has no bucket. That raises an IndexError.
    • Wrong order is fine. The answer can come back in any order. For [5, 5, 5, 2, 2, 3] with k = 1 the answer is [5].

    Testing

    • nums = [1, 1, 1, 2, 2, 3], k = 2 gives [1, 2].
    • nums = [1], k = 1 gives [1].
    • nums = [4, -1, 4, -1, 7, 4, -1, 9], k = 2 gives [4, -1].
    • nums = [5, 5, 5, 2, 2, 3], k = 1 gives [5].
    • nums = [1, 2, 3], k = 3 gives [1, 2, 3].
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free