Chapter 08 - Heaps
A heap always knows its largest (or smallest) element. Insertion and removal cost \(O(\log n)\).
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::BinaryHeapis a max-heap. Wrap values instd::cmp::Reverseto get a min-heap.- To order by a key, push tuples such as
(frequency, Reverse(word)), or implementOrdon a small struct. f64does not implementOrd, so it cannot go into aBinaryHeapdirectly.
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.