347. Top K Frequent Elements
At a Glance
- Topic: arrays-hashing
- Pattern: Top-K / Heap (bucket sort variant)
- Difficulty: Medium
- Companies: Amazon, Google, Meta, LinkedIn, Bloomberg
- Frequency: High
- LeetCode: 347
Problem (one-liner)
Given an integer array numbers and an integer k, return the k most frequent elements. Order in the output is not specified unless the problem says so.
Recognition Cues
- "Top k frequent", "k most common"
- Frequency count + selection (heap, bucket, or quickselect)
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — count with map, sort all unique by count —
O(n + u log u)time. - Better — min-heap of size
kon (count, value) —O(n log k)time /O(n)space. - Optimal (interview favorite) — bucket by frequency: index = frequency,
O(n)time /O(n)space; or heapO(n log k).
Optimal Solution
Go
package main
func topKFrequent(numbers []int, topK int) []int {
counts := make(map[int]int)
for _, value := range numbers {
counts[value]++
}
buckets := make([][]int, len(numbers)+1)
for value, frequency := range counts {
buckets[frequency] = append(buckets[frequency], value)
}
result := make([]int, 0, topK)
for frequency := len(buckets) - 1; frequency >= 0 && len(result) < topK; frequency-- {
for _, value := range buckets[frequency] {
result = append(result, value)
if len(result) == topK {
return result
}
}
}
return result
}JavaScript
function topKFrequent(numbers, topK) {
const counts = new Map();
for (const value of numbers) {
counts.set(value, (counts.get(value) || 0) + 1);
}
const buckets = Array.from({ length: numbers.length + 1 }, () => []);
for (const [value, frequency] of counts) {
buckets[frequency].push(value);
}
const result = [];
for (let frequency = buckets.length - 1; frequency >= 0 && result.length < topK; frequency--) {
for (const value of buckets[frequency]) {
result.push(value);
if (result.length === topK) {
return result;
}
}
}
return result;
}Walkthrough
Input: numbers = [1,1,1,2,2,3], topK = 2
| step | action | counts / buckets (conceptual) |
|---|---|---|
| 1 | count frequencies | 1→3, 2→2, 3→1 |
| 2 | bucket index = frequency | bucket[3]={1}, bucket[2]={2}, bucket[1]={3} |
| 3 | scan frequency high→low | take bucket[3] → 1 |
| 4 | still need one more | take bucket[2] → 2 |
| 5 | result length 2 → [1, 2] | done |
Invariant: bucket frequency holds all values that appear exactly frequency times.
Edge Cases
kequals number of distinct elements → return all distinct.- Single value repeated
ntimes,k = 1. - All unique → any
kvalues (each frequency 1).
Pitfalls
- Using max-heap incorrectly (min-heap of size
kis standard for top-k by frequency). - Off-by-one on bucket size (
len(numbers)+1).
Similar Problems
- 215. Kth Largest Element in an Array — selection / heap.
- 238. Product of Array Except Self — array indexing tricks.
- 001. Two Sum — frequency maps.
Variants
- Break ties by smaller value.
- Stream of elements — use heap or counting sketch.
Mind-Map Tags
#heap #bucket-sort #frequency #hashmap #top-k
Last updated on
Spotted something unclear or wrong on this page?