Top K Frequent Elements

Medium

Topics
ArrayHash TableHeapBucket Sort

Given an integer array nums and an integer k, return the k most frequent elements. On this judge the answer is returned sorted in ascending order, and the inputs guarantee the k most frequent elements are unambiguous.

Example 1

nums111223
counts1×32×23×1
top 2 by frequency
The distinct values are ranked by how often they occur, and the 2 most frequent are returned — the values themselves, not their counts. Any order among them is accepted, so the answer here is [1, 2] in some order.
Top row is the input; chips are the distinct values with their counts.
Input:  nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2

nums1
counts1×1
top 1 by frequency
Input:  nums = [1], k = 1
Output: [1]

Constraints

  • 1 <= nums.length <= 10^5
  • k is in the range [1, number of distinct elements]
  • The k most frequent elements are unique.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Count frequencies, then you need the k largest by count. A full sort is O(n log n); a bucket indexed by frequency (which is at most n) gets you there in O(n).

Approach

  1. Count each value’s frequency in a hash map.
  2. Place values into buckets indexed by their frequency.
  3. Walk buckets from high frequency down, collecting until you have k values.

Dry Run

nums = [1, 1, 1, 2, 2, 3]   k = 2
counts   {1: 3, 2: 2, 3: 1}
buckets indexed BY FREQUENCY rather than by value:
  f=0   []
  f=1   [3]
  f=2   [2]
  f=3   [1]
  f=4, 5, 6   []
walk down from the highest frequency:
  bucket f=3   take 1    r = [1]
  bucket f=2   take 2    r = [1, 2]   k reached, return
answer 1 2
The bucket array works because frequency is BOUNDED: no value can occur more than
n times, so n + 1 lists cover every possible count and "sort by frequency" becomes
an array index. No two counts are ever compared, which is exactly where the log
factor goes.
The array is deliberately oversized -- f=4, 5 and 6 are empty here and simply
walked past. Sizing it to the largest observed count would save a little memory
and change nothing asymptotically.
One honest caveat, measured rather than assumed: in CPython a heap-based
Counter.most_common(k) is FASTER than this bucket loop -- 0.065s against 0.120s at
n = 400000 with k = 100 -- because nlargest is C and the bucket walk is
interpreted Python. O(n) beats O(n log k) on paper and loses on the clock at these
sizes. Both facts are worth being able to state.

Complexity

  • Time — O(n): counting and bucket placement are linear; bucket scan is bounded by n.
  • Space — O(n): the count map and buckets.

Common Pitfalls

  • A heap of size k gives O(n log k) — also fine, but bucket sort avoids the log factor.
  • Avoiding the log factor does not always make it faster. Measured in CPython at n = 400000 with k = 100, Counter.most_common(k) — which is heapq.nlargest underneath — takes 0.065s against 0.120s for the bucket walk, because one is C and the other is interpreted. State the asymptotics, but do not claim a wall-clock win you have not measured.

Full Solution — all languages

class Solution:
    def topKFrequent(self, nums, k):
        from collections import Counter
        c = Counter(nums)
        # bucket by frequency: O(n)
        buckets = [[] for _ in range(len(nums) + 1)]
        for v, f in c.items():
            buckets[f].append(v)
        r = []
        for f in range(len(buckets) - 1, -1, -1):
            for v in buckets[f]:
                r.append(v)
                if len(r) == k:
                    return r
        return r
SensAI
Beta
Tap the mic to stop voice mode