Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Heaps & Priority Queues/Top-K Elements

Technique

Bucket / Counting Sort

Distribute items into buckets by a bounded key (frequency, value range) so ordering is O(n + range) instead of O(n log n).

Learn firstHash Map / Hash Set Lookup
0%
mastery
0/5 solved
Practise nextH-Index
IdeaPracticePitfalls

Recognise it

The signal

keys bounded by n (frequencies)

  1. 1Brute force

    Comparison sort O(n log n).

  2. 2The observation

    Comparison sorting: bounded integer keys can be indexed directly.

  3. 3Why it works

    Bucket b holds exactly the items with key b (or in range b).

Reach for it when

  • +top-k frequent in O(n)
  • +maximum gap between sorted elements in O(n)

Not when

  • ×unbounded keys
  • ×need stable order of complex comparators

Practice

Next

H-Index

0/5 solved
  • H-IndexGoogle, AdobeMedium
  • Custom Sort StringMetaMedium
  • Top K Frequent ElementsAmazon, MetaMedium
  • Sort Characters By FrequencyAmazon, UberMedium
  • Sliding Window ModeCSESMedium

Pitfalls

Misconceptions

  • !thinking heaps are required for top-k frequent
Go deeperresources

Resources

  • Heap visualizerVisuAlgo · tool
  • Heap cheatsheetTech Interview Handbook · article
  • std::priority_queuecppreference · docs
  • Find Median from Data Stream editorialLeetCode · editorial
  • Heaps and Heap SortAbdul Bari · video
TodayReviewPatternsProblems