Skip to content
Sorting & SearchingIntermediate

Bucket Sort / Top-K

Use a heap (priority queue) or bucket sort to efficiently find the K largest/smallest/most frequent elements.

Problem: Top K Frequent Elements

Find the 2 most frequent elements in [1, 1, 1, 2, 2, 3].

Initial Array

Find the top 2 most frequent elements in [1,1,1,2,2,3]

Step 1/7
Speed:

When to Use

  • Find top K elements
  • K most frequent
  • Kth largest/smallest
  • Sort by frequency

Key Indicators

  • "Top K", "Kth largest/smallest"
  • Frequency-based selection
  • Partial sorting needed

Complexity

Time

O(n log k) heap / O(n) bucket sort

Space

O(n)

Common Problems

Top K Frequent ElementsKth Largest ElementSort Characters By FrequencyK Closest Points to OriginReorganize String

Code

# Heap approach:
heap = []
for element in arr:
    heappush(heap, element)
    if len(heap) > k:
        heappop(heap)
# Or bucket sort for frequency:
buckets = [[] for _ in range(n+1)]
for num, freq in counter.items():
    buckets[freq].append(num)

Want all 29 patterns with detailed visual walkthroughs?

The complete book includes 84 practice problems, full decision tree, and illustrated step-by-step solutions.

Book Coming Soon ($4.99)