Skip to main content
05

Top K Frequent Elements

Mediumhash mapbucket sortheap

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Arrays & HashingRead the beginner guide

Given an integer array nums and an integer k, return the k most frequent values. You may return them in any order.

Understand the problem

  • Frequency means "how many times a value appears". In [1, 1, 1, 2, 2, 3], the value 1 has frequency 3, 2 has frequency 2, and 3 has frequency 1.
  • The k most frequent means: rank the distinct values from most common to least common, and take the first k.
  • You return the values, not their counts.

Example 1

text
Input:  nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]

1 appears 3 times and 2 appears 2 times. Those are the top two. 3 (1 time) doesn't make the cut.

Example 2

text
Input:  nums = [7], k = 1
Output: [7]

Example 3

text
Input:  nums = [4, 4, 5, 5, 5, 6], k = 1
Output: [5]

5 appears 3 times, more than any other value.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= the number of distinct values in nums
  • The answer is unique: there is never a tie for the k-th place.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Count every value, put each value in a "bucket" numbered by its count, then read the buckets from the highest count down until you have k values.

    The naive approach (and why it's slow)

    1. Count each value with a hash map.
    2. Sort the distinct values by their count, biggest first.
    3. Take the first k.

    This is correct and a perfectly good first answer in an interview. The slow part is the sort: O(n log n). The problem hints that we can do better.

    The key insight

    Sorting is a general tool: it can order any numbers. But our counts aren't any numbers. A value can appear at most n times (if the whole array is that value), so every count is a whole number from 1 to n.

    When the things you're sorting are small whole numbers, you can skip sorting and use them as positions in an array. This trick is called bucket sort:

    • Make an array buckets with n + 1 slots, each holding a list.
    • buckets[c] holds every value that appears exactly c times.
    • Reading the array from the end gives you values from most to least frequent.

    Step by step

    nums = [1, 1, 1, 2, 2, 3], k = 2, so n = 6.

    1. Count with a hash map:

    text
    { 1: 3, 2: 2, 3: 1 }

    2. Bucket each value by its count (slots 0 to 6):

    Count (slot)0123456
    Values[3][2][1]

    3. Walk from the highest slot down, collecting until we have k = 2:

    SlotValues in itResult afterwards
    6(empty)[]
    5(empty)[]
    4(empty)[]
    31[1]
    22[1, 2] ✅ stop

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). Counting is one pass. Putting values in buckets is one pass over the distinct values. Walking the buckets visits n + 1 slots, and each value is in exactly one of them.
    • Memory: O(n) for the counts and the buckets.

    Common mistakes

    • Making the bucket array too small. It needs n + 1 slots (0 through n), because a value can appear n times.
    • Returning counts instead of values. The buckets are indexed by count, but hold values. Return what's inside them.
    • Not stopping at k. A bucket can hold several values. Stop as soon as the result has k of them.

    Going deeper

    • A min-heap of size k: keep only the k most frequent seen so far, for O(n log k). This is the usual answer when the data arrives as a stream, or when n is huge and k is small. JavaScript has no built-in heap; Python has heapq (heapq.nlargest(k, counts, key=counts.get)). Heaps get their own category later.
    • Bucket sort only works because counts are bounded by n. Being able to say why it works is what interviewers look for.

    Reference solution

    js
    /**
     * @param {number[]} nums
     * @param {number} k
     * @return {number[]}
     */
    export default function topKFrequent(nums, k) {
      // 1. Count: value -> how many times it appears.
      const counts = new Map()
      for (const num of nums) counts.set(num, (counts.get(num) ?? 0) + 1)
    
      // 2. Bucket: buckets[c] holds every value that appears exactly c times.
      //    A count can be at most nums.length, so we need nums.length + 1 slots.
      const buckets = Array.from({ length: nums.length + 1 }, () => [])
      for (const [num, count] of counts) buckets[count].push(num)
    
      // 3. Walk from the highest count down, collecting values until we have k.
      const result = []
      for (let count = buckets.length - 1; count > 0 && result.length < k; count--) {
        for (const num of buckets[count]) {
          result.push(num)
          if (result.length === k) break
        }
      }
      return result
    }
    ts
    export default function topKFrequent(nums: number[], k: number): number[] {
      // 1. Count: value -> how many times it appears.
      const counts = new Map<number, number>()
      for (const num of nums) counts.set(num, (counts.get(num) ?? 0) + 1)
    
      // 2. Bucket: buckets[c] holds every value that appears exactly c times.
      //    A count can be at most nums.length, so we need nums.length + 1 slots.
      const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => [])
      for (const [num, count] of counts) buckets[count].push(num)
    
      // 3. Walk from the highest count down, collecting values until we have k.
      const result: number[] = []
      for (let count = buckets.length - 1; count > 0 && result.length < k; count--) {
        for (const num of buckets[count]) {
          result.push(num)
          if (result.length === k) break
        }
      }
      return result
    }
    python
    from collections import Counter
    
    
    def top_k_frequent(nums: list[int], k: int) -> list[int]:
        # 1. Count: Counter([1, 1, 2]) == {1: 2, 2: 1}
        counts = Counter(nums)
    
        # 2. Bucket: buckets[c] holds every value that appears exactly c times.
        #    A count can be at most len(nums), so we need len(nums) + 1 slots.
        buckets = [[] for _ in range(len(nums) + 1)]
        for num, count in counts.items():
            buckets[count].append(num)
    
        # 3. Walk from the highest count down, collecting values until we have k.
        result = []
        for count in range(len(buckets) - 1, 0, -1):
            for num in buckets[count]:
                result.append(num)
                if len(result) == k:
                    return result
        return result