Pattern #29
Top K Elements
Important interview questions, thinking patterns, Top K Heap size limits, Bucket Sort frequency optimization, Quickselect tradeoffs, and Go rules.
Must Solve
15 core questions — solve these first.
- 1.Kth Largest Element in an ArrayMin Heap size K in O(N log K) time or Quickselect in O(N)medium
- 2.Top K Frequent ElementsHashMap frequency + Min Heap size K or Bucket Sort in O(N)medium
- 3.K Closest Points to OriginMax Heap size K storing (dist = x^2 + y^2, point)medium
- 4.Kth Largest Element in a StreamMaintain Min Heap of size Keasy
- 5.Find K Pairs with Smallest SumsMin Heap storing (u + v, i, j) index pairsmedium
- 6.Kth Smallest Element in a Sorted MatrixMin Heap row candidates or Binary Search on rangemedium
- 7.Find K Closest ElementsBinary search window + 2 pointers or Max Heap distancemedium
- 8.Top K Frequent WordsMin Heap size K with custom tie-breaker alphabetical comparatormedium
- 9.Merge K Sorted ListsMin Heap storing candidate node pointers from each listhard
- 10.Kth Smallest Number in Multiplication TableBinary Search on answer range 1..m*nhard
- 11.Kth Smallest Prime FractionMin Heap storing (a/b, i, j) fraction pairsmedium
- 12.Sort Characters By FrequencyFrequency HashMap + Bucket Sort or Max Heapmedium
- 13.Reorganize StringMax Heap of character counts + previous character holdmedium
- 14.Find Median from Data StreamTwo Heaps: Max Heap (lower half) + Min Heap (upper half)hard
- 15.K Closest Points to OriginMax Heap of size K keeping smallest distancesmedium
Also Important
9 more questions worth practicing.
- 16.Kth Smallest Element in a BSTInorder traversal with counter Kmedium
- 17.Ugly Number IIMin Heap generating numbers multiplied by 2, 3, 5 + HashSetmedium
- 18.Smallest Range Covering Elements from K ListsMin Heap storing current elements across K listshard
- 19.Maximum Performance of a TeamSort by efficiency + Min Heap of speed sum for top K engineershard
- 20.Total Cost to Hire K WorkersTwo Min Heaps for first & last candidate windowshard
- 21.IPOSort projects by capital + Max Heap for available profitshard
- 22.Minimum Cost to Connect SticksMin Heap combining two smallest sticks repeatedly (Greedy)medium
- 23.K Weakest Rows in a MatrixMax Heap size K storing (soldier_count, row_index)easy
- 24.Find Subsequence of Length K With Largest SumMin Heap size K storing (value, index) + sort by indexeasy
How to Think
- Need K largest elements?Min Heap of size K (evict root when size > K)
- Need K smallest elements?Max Heap of size K (evict root when size > K)
- Need Top K by frequency?Hash Map + Min Heap size K or Bucket Sort
- Need closest K items?Distance (x² + y²) + Max Heap of size K
- K is much smaller than N?Don't sort all N items! Use Heap O(N log K)
Go Top K Min Heap Pattern Template
Top K Eviction Loop in Go
// Maintain Min Heap of size K for Top K Largest elements
h := &IntHeap{}
heap.Init(h)
for _, val := range nums {
heap.Push(h, val)
// When size exceeds K, evict the weakest candidate at root!
if h.Len() > k {
heap.Pop(h)
}
}
// h now contains the Top K largest elements in O(N log K) time!
// Root h[0] is the K-th largest element.👉 Time: O(N log K) | Auxiliary Space: O(K)
5 Core Top K Sub-Patterns
Use Min Heap of size K. Root is the weakest candidate of the top K, evicted when size > K.
Use Max Heap of size K. Root is the largest candidate of the top K, evicted when size > K.
Build frequency HashMap $\implies$ Push (val, count) into Min Heap size K or use Bucket Sort.
Compute distance $x^2 + y^2 \implies$ Max Heap size K evicting largest distance candidate.
Bucket Sort for Top K Frequency (O(N) Time Optimization)
Instead of using a Heap in O(N log K) time for Top K Frequent Elements, map frequencies to an array of slices where buckets[count] = [values]:
// 1. Build frequency map
counts := map[int]int{}
for _, num := range nums { counts[num]++ }
// 2. Build buckets array where index = frequency count
buckets := make([][]int, len(nums)+1)
for num, count := range counts {
buckets[count] = append(buckets[count], num)
}
// 3. Scan buckets from right to left (highest frequency to lowest)
result := []int{}
for i := len(buckets)-1; i >= 0 && len(result) < k; i-- {
if len(buckets[i]) > 0 {
result = append(result, buckets[i]...)
}
}👉 Total Time: O(N) linear time & space!
Top K Largest → Min Heap size K (evict weakest root)
Top K Smallest → Max Heap size K (evict largest root)
Top K Frequent → HashMap + Min Heap size K OR Bucket Sort O(N)
Distance check → Use x² + y² (No square root needed!)💡 Golden Rule: "Keep only the K best candidates, and always make the weakest one easy to remove."
Common Interview Mistakes
Using Max Heap forces storing all N items (O(N log N)). Use a Min Heap of size K (O(N log K)) to evict the weakest item at root!
Sorting all N elements takes O(N log N) time when $K \ll N$. Always use a size-K Heap (O(N log K)).
A heap array is NOT sorted! If the problem requires sorted K output, sort the final K items in O(K log K) time.
Computing math.Sqrt(x^2 + y^2) for K Closest Points. Comparing squared distance x^2 + y^2 is faster and avoids float precision issues!
Interview Rules
- 1. K largest elements? → Min Heap size K (
O(N log K)time,O(K)space) - 2. K smallest elements? → Max Heap size K
- 3. Kth largest item only? → Min Heap top OR Quickselect (
O(N)average) - 4. Top K frequent? → Frequency Map + Heap OR Bucket Sort (
O(N)time) - 5. K closest items? → Distance
x^2 + y^2+ Max Heap size K - 6. Weakest candidate rule → Evict root whenever heap size exceeds K
- 7. Sort final output? → Heap is not sorted; sort the K popped items in
O(K log K)if required - 8. K close to N? → If $K \approx N$, full sorting in
O(N log N)is simpler and reasonable
Small Rules
- Rule 1: Don't automatically sort all N items when K is much smaller than N.
- Rule 2:Bound heap size strictly to K (evict root when size > K).
- Rule 3: Clearly define what "best" means (largest, smallest, distance, frequency, tie-breakers).
- Rule 4: Ask: "Which of my current K candidates should leave first?" That decides Min vs Max heap.
- Rule 5: Use Bucket Sort for frequency counting to achieve O(N) linear time performance.
Production Thinking
Top Products by Sales → Extract top 100 products from multi-million catalog without full sorting
Monitoring Latency Spikes → Track 20 slowest request latencies across continuous server stream
Error Telemetry Analytics → HashMap error counts + Top K frequent error codes
Search Candidate Ranking → Score candidate relevance and return Top 20 results in real-time
Remember This
Top K Largest → Min Heap K
Top K Smallest → Max Heap K
Top K Frequent → Map + Heap / Bucket Sort
K Closest → Distance + Heap
Only Kth item → Quickselect
Heap too big → Remove weakest
N huge, K small → Don't sort everything
Heap approach → O(n log k)💡 Golden Rule: "Keep only the K best candidates, and always make the weakest one easy to remove."