Chapter 08 - Heaps

A heap always knows its largest (or smallest) element. Insertion and removal cost \(O(\log n)\).

Coding Interview Patterns book cover with the Rust logo and a CHAP 08 label, the chapter on heaps

This page is the entry point of chapter 8 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.

The idea

A heap is a priority queue. To keep the k best items of a stream, we keep a heap of size k and drop the worst one each time it overflows. To merge k sorted lists, a heap holds the current head of each list. To follow the median of a stream, two heaps hold the lower half and the upper half.

When to reach for it

  • Top k, k most frequent, kth largest questions.
  • Merging several sorted sources.
  • Data that arrives as a stream, where sorting everything again is not an option.

In Rust

  • std::collections::BinaryHeap is a max-heap. Wrap values in std::cmp::Reverse to get a min-heap.
  • To order by a key, push tuples such as (frequency, Reverse(word)), or implement Ord on a small struct.
  • f64 does not implement Ord, so it cannot go into a BinaryHeap directly.

Problems in this chapter

  • p145 - K Most Frequent Strings: K Most Frequent Strings (Heaps) solved in Rust: return the k most frequent strings of an array, by descending frequency, ties in alphabetical order.
  • p151 - Combine Sorted Linked Lists: Combine Sorted Linked Lists (Heaps), solved in Rust. Given k linked lists, each sorted ascending, combine them in one sorted linked list.
  • p155 - Median of an Integer Stream: Median of an Integer Stream (Heaps), solved in Rust. Design a structure where we can add i32 from a data stream and get the median.
  • bonus080 - Sort K-Sorted Array: Sort K-Sorted Array (Heaps), solved in Rust. Given an i32 array where each element is at most k positions away from its sorted position, sort the array in a…

Other chapters

All the chapters, with every problem, are listed on the series page.


Back to top

Published on: Dec 1 2026 at 10:00 AM | Last updated: Dec 1 2026 at 10:32 AM

Copyright © 1964-2026 - 40tude