Reach for a heap when a problem keeps asking for the smallest or largest of what's left — while values are still being added or removed. Sorting answers that question once. A heap answers it again and again, at O(log n) per change.
That last row is the whole reason heaps exist. When a problem mixes adding values with taking out the smallest (or largest), the other two choices each have one operation that costs O(n) — and a loop that does it n times costs O(n²).
Free account
Sign up to read the rest of this lesson: 6 more sections, 4 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come