Part 17 / Topic 10 of 12
PriorityQueue as a heap
A heap keeps "the smallest (or largest) item" available in O(log n) insert/remove, without ever fully sorting the rest of the data. Kotlin's standard library has no native heap type — java.util.PriorityQueue is the heap a working Kotlin developer reaches for, and there is no separate "write your own Heap class" step here the way there was for linked lists and trees: the library class is the data structure, array-backed internally, and understanding what it guarantees (cheap peek-the-smallest, not sorted iteration) is the whole lesson.
Think of a hospital triage queue: the next patient seen is always the most urgent one currently waiting, not the one who arrived first — and a new, more urgent arrival can jump ahead without the whole queue being re-sorted.
val minHeap = PriorityQueue<Int>() // smallest out first
val maxHeap = PriorityQueue<Int>(Collections.reverseOrder<Int>()) // largest out first
$ kotlinc HeapDemo.kt -include-runtime -d heap.jar
$ java -jar heap.jar
-- min-heap (default): smallest first out --
poll order: 15 20 40 55 80 90
-- max-heap: pass Collections.reverseOrder() as the comparator --
poll order: 90 80 55 40 20 15
-- top-k with a BOUNDED max-heap: cheapest 3 of many fares, without a full sort --
all fares: [340, 120, 560, 90, 310, 70, 450, 210, 180]
cheapest 3 fares (O(n log k), never fully sorted all 9): [70, 90, 120]
-- custom comparator: a support ticket queue, most urgent first --
served order: T-101(p1) T-103(p1) T-102(p2) T-104(p3)
The bounded top-k trick is the one worth remembering cold: to find the k smallest values among many, keep a max-heap bounded to size k — every time it grows past k, evict the current largest (poll()), so only the k smallest survive. This is O(n log k) instead of sorting everything (O(n log n)), and it's the exact mechanism the trending-posts build below uses to avoid ranking an entire feed just to show the top 3. Note the comparator spelling: compareBy { it.priority } reads cleanly for a custom type, same Comparator machinery as Collections.reverseOrder() underneath.
⚠️ It's easy to get min-heap/max-heap backwards for top-k. If you want the
ksmallest, bound a max-heap (so the biggest of your keepers is always the one you can cheaply evict). If you want theklargest, bound a min-heap instead. Say out loud which one you're keeping before writing the comparator.
Full program: examples/heaps/HeapDemo.kt.
Real-world build 2: trending posts
"Trending posts" is the top-k ranking problem every feed has: count likes per post (hashing, section 2), then keep only the top k by count without sorting the whole feed (the bounded-heap trick above, applied to real objects instead of a bare IntArray).
val topK = PriorityQueue<TrendingEntry>(compareBy { it.likeCount }) // min-heap: smallest count easiest to evict
for ((postId, likes) in likeCounts) {
topK.offer(TrendingEntry(posts.getValue(postId), likes))
if (topK.size > k) topK.poll() // drop the current smallest of the k being kept
}
$ kotlinc TrendingPostsDemo.kt -include-runtime -d trending.jar
$ java -jar trending.jar
posts: 5, total like events: 2320
-- top 3 trending posts right now --
#1 meera_eats 950 likes - "Best vada pav in Dadar"
#2 priya_travels 710 likes - "Sunrise at Hampi"
#3 ravi_k 420 likes - "Monsoon trek, Lonavala"
-- a new post goes viral: feed updates without re-ranking everything --
#1 kiran.d 1560 likes - "Office cricket match, we won"
#2 meera_eats 950 likes - "Best vada pav in Dadar"
#3 priya_travels 710 likes - "Sunrise at Hampi"
Here the heap keeps the k largest counts, so it's bounded with a min-heap (the opposite of the "cheapest fares" example above, which wanted the k smallest and used a max-heap) — the comparator you pick always follows from which end you need to evict cheaply, not from a rule to memorize.
Full program: examples/heaps/TrendingPostsDemo.kt.
Done here? The practice set for Part 17 — including the solutions — is on the part page.