⚡Flashcard Drill➔
NeetCode #98LC-347MediumArrays & HashingBlind 75NC 150NC 250
← Back to All Problems

#98 · #347 · Top K Frequent Elements(前 K 个高频元素)

📌 Problem Statement & Constraints

Given an integer array nums and an integer k, return the k most frequent elements in any order. Constraints: 1 <= nums.length <= 10^5, k is in the range [1, number of distinct elements]; the answer is guaranteed unique.

💡 Core Algorithmic Approaches

  1. First build a frequency map with Counter -- this is unavoidable and costs O(n).
  2. Option A (optimal): bucket sort by frequency. The maximum possible frequency is n, so create n + 1 buckets and place each value into buckets[freq]. Then walk buckets from high to low, collecting until you have k values. This is O(n).
  3. Option B: a min-heap of size k keyed by frequency, giving O(n log k).
  4. Option C: heapq.nlargest(k, counter, key=counter.get) -- concise and O(n log k).
  5. Note the answer is unique, so no tie-breaking rule is needed.

💻 Benchmark Python3 Implementation

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        from collections import Counter
        freq = Counter(nums)
        n = len(nums)
        buckets = [[] for _ in range(n + 1)]      # index = frequency
        for value, f in freq.items():
            buckets[f].append(value)
        res = []
        for f in range(n, 0, -1):                 # scan high frequency first
            for value in buckets[f]:
                res.append(value)
                if len(res) == k:
                    return res
        return res


# Heap variant: O(n log k) time, O(n) space, shorter code
class Solution2:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        import heapq
        from collections import Counter
        freq = Counter(nums)
        return heapq.nlargest(k, freq, key=freq.get)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n) with bucket sort: counting is O(n), filling buckets is O(distinct), and the descending scan stops as soon as k values are collected. The heap variant is O(n log k).
💾 Space Complexity
O(n) for the frequency map and the bucket array. The heap variant uses O(distinct) for the map plus O(k) for the heap.

⚠️ Interview Pitfalls & Follow-ups

  • sorted(freq.items(), key=lambda kv: -kv[1])[:k]: correct but O(n log n). Mention it, then offer bucket sort or a heap to show you know the trade-off.
  • Sizing the bucket array as max(freq.values()) + 1: also works, but n + 1 is simpler and always safe since no frequency can exceed n.
  • Using a max-heap of all distinct values: it is O(n log n) and defeats the purpose of the heap size limit.
  • Assuming ties must be broken deterministically: the problem guarantees a unique answer, so you do not need a tie-break rule.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

前 K 个高频元素

给你一个整数数组 nums 和一个整数 k,请你返回其中出现频率前 k 高的元素。你可以按任意顺序返回答案。约束:1 ≤ nums.length ≤ 10^5;k 的取值范围是 [1, 数组中不相同的元素的个数];题目数据保证答案唯一。进阶要求:算法的时间复杂度必须优于 O(n log n)。

核心要点

  • 第一步:统计频率 。用哈希表或 collections.Counter 统计每个元素的出现次数,O(n)。
  • 第二步:选出 Top-K 。有三种主流做法:① 小顶堆维护大小为 k 的候选集;② 桶排序(按频率分桶);③ 快速选择(quickselect)。
  • 小顶堆法 :遍历频率表,把元素压入小顶堆;堆大小超过 k 时弹出堆顶(当前频率最小的)。最终堆内即前 k 高频。时间 O(n log k)。
  • 桶排序法(最优) :频率的取值范围是 [1, n],因此可以开 n+1 个桶,把「频率 = i」的元素放进第 i 个桶;从高频桶往低遍历,收集到 k 个即可。时间 O(n),突破排序下界。
  • 为什么桶排序能到 O(n) :它绕开了「基于比较的排序」的 Ω(n log n) 下界——不比较元素,而是利用频率是 有界整数 这一额外信息做计数。

常见陷阱

  • 桶的数量开错 :桶的下标是频率,最大频率可达 n,因此必须开 n+1 个桶(下标 0..n),开成 n 个会在「所有元素相同」时越界。
  • 误用大顶堆 :要保留「前 k 高频」,应该用 小顶堆 淘汰频率最小的;用大顶堆会导致弹出的是最高频元素,逻辑正好相反。
  • 在 Python 里堆元组踩坑 : heapq 按元组字典序比较,把 (cnt, val) 而非 (val, cnt) 入堆,否则当频率相同时会比较元素值,虽不影响本题结果但语义易错。
  • 被追问 数据流场景 时答不上来:桶排序需要全量数据,流式场景应改用小顶堆或 Count-Min Sketch 等近似结构。

参考实现

from collections import Counter

class Solution:
    def topKFrequent(self, nums: list[int], k: int) -> list[int]:
        freq = Counter(nums)
        n = len(nums)
        # buckets[i] 存放出现次数恰好为 i 的所有元素
        buckets = [[] for _ in range(n + 1)]
        for val, cnt in freq.items():
            buckets[cnt].append(val)
        res = []
        for i in range(n, 0, -1):           # 从最高频往低收集
            for val in buckets[i]:
                res.append(val)
                if len(res) == k:
                    return res
        return res

# 小顶堆版本(O(n log k),k 远小于 n 时更省空间):
# import heapq
# heap = []
# for val, cnt in freq.items():
#     heapq.heappush(heap, (cnt, val))
#     if len(heap) > k:
#         heapq.heappop(heap)
# return [v for _, v in heap]