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. 1.Kth Largest Element in an Array
    medium
  2. 2.Top K Frequent Elements
    medium
  3. 3.K Closest Points to Origin
    medium
  4. 4.Kth Largest Element in a Stream
    easy
  5. 5.Find K Pairs with Smallest Sums
    medium
  6. 6.Kth Smallest Element in a Sorted Matrix
    medium
  7. 7.Find K Closest Elements
    medium
  8. 8.Top K Frequent Words
    medium
  9. 9.Merge K Sorted Lists
    hard
  10. 10.Kth Smallest Number in Multiplication Table
    hard
  11. 11.Kth Smallest Prime Fraction
    medium
  12. 12.Sort Characters By Frequency
    medium
  13. 13.Reorganize String
    medium
  14. 14.Find Median from Data Stream
    hard
  15. 15.K Closest Points to Origin
    medium

Also Important

9 more questions worth practicing.

  1. 16.Kth Smallest Element in a BST
    medium
  2. 17.Ugly Number II
    medium
  3. 18.Smallest Range Covering Elements from K Lists
    hard
  4. 19.Maximum Performance of a Team
    hard
  5. 20.Total Cost to Hire K Workers
    hard
  6. 21.IPO
    hard
  7. 22.Minimum Cost to Connect Sticks
    medium
  8. 23.K Weakest Rows in a Matrix
    easy
  9. 24.Find Subsequence of Length K With Largest Sum
    easy

How to Think

  1. Need K largest elements?Min Heap of size K (evict root when size > K)
  2. Need K smallest elements?Max Heap of size K (evict root when size > K)
  3. Need Top K by frequency?Hash Map + Min Heap size K or Bucket Sort
  4. Need closest K items?Distance (x² + y²) + Max Heap of size K
  5. 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

1. K Largest Elements

Use Min Heap of size K. Root is the weakest candidate of the top K, evicted when size > K.

2. K Smallest Elements

Use Max Heap of size K. Root is the largest candidate of the top K, evicted when size > K.

3. Top K Most Frequent

Build frequency HashMap $\implies$ Push (val, count) into Min Heap size K or use Bucket Sort.

4. K Closest Items

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!

Visual Memory Rule
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

1. Using Max Heap for Top K Largest

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!

2. Sorting All N Elements

Sorting all N elements takes O(N log N) time when $K \ll N$. Always use a size-K Heap (O(N log K)).

3. Expecting Heap Output to be Sorted

A heap array is NOT sorted! If the problem requires sorted K output, sort the final K items in O(K log K) time.

4. Using Expensive Distance Square Root

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. 1. K largest elements? → Min Heap size K (O(N log K) time, O(K) space)
  2. 2. K smallest elements? → Max Heap size K
  3. 3. Kth largest item only? → Min Heap top OR Quickselect (O(N) average)
  4. 4. Top K frequent? → Frequency Map + Heap OR Bucket Sort (O(N) time)
  5. 5. K closest items? → Distance x^2 + y^2 + Max Heap size K
  6. 6. Weakest candidate rule → Evict root whenever heap size exceeds K
  7. 7. Sort final output? → Heap is not sorted; sort the K popped items in O(K log K) if required
  8. 8. K close to N? → If $K \approx N$, full sorting in O(N log N) is simpler and reasonable

Small Rules

  1. Rule 1: Don't automatically sort all N items when K is much smaller than N.
  2. Rule 2:Bound heap size strictly to K (evict root when size > K).
  3. Rule 3: Clearly define what "best" means (largest, smallest, distance, frequency, tie-breakers).
  4. Rule 4: Ask: "Which of my current K candidates should leave first?" That decides Min vs Max heap.
  5. Rule 5: Use Bucket Sort for frequency counting to achieve O(N) linear time performance.

Production Thinking

Top Products by SalesExtract top 100 products from multi-million catalog without full sorting

Monitoring Latency SpikesTrack 20 slowest request latencies across continuous server stream

Error Telemetry AnalyticsHashMap error counts + Top K frequent error codes

Search Candidate RankingScore 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."