Builds onSorting as a tool
01The idea
A heap, also called a priority queue, always gives you its smallest item. Adding an item and removing the smallest both take O(log n). Looking at the smallest without removing it takes O(1).
Inside, a heap is a tree stored in an array, kept so that every parent is at most its children. You never need to touch that tree yourself. Use the library:
- Python:
heapq.heappush(h, x),heapq.heappop(h),h[0]to look, andheapq.heapify(h)to turn a list into a heap in O(n). It is a min-heap. For a max-heap, push negative values. - Java:
PriorityQueue<Integer>withadd,pollandpeek. It is a min-heap by default. PassCollections.reverseOrder()for a max-heap.
A sorted list also gives you the smallest item. A heap is better when items keep arriving while you work. Each new item costs O(log n), where keeping a list sorted costs O(n) per insert.
The top K trick appears in many problems. To keep the K largest items of a stream, keep a min-heap of size K. When it grows past K, pop the smallest. The heap then holds the K largest items seen so far, and its top is the Kth largest. That takes O(n log K).
02How to spot it
Use a heap when:
- the problem says "K largest", "K smallest", "Kth largest" or "K most frequent"
- you repeatedly need the smallest or largest item while new items keep arriving
- you merge several sorted lists and always need the smallest head
- a greedy rule says "always take the cheapest", "the earliest ending" or "the shortest", and the pool changes as you go
If you need the smallest item only once, a single scan is enough. If the items never change, sorting once may be simpler. The heap earns its place when you pull the smallest item many times from a changing pool.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue