Intro

Heaps are Tree-based data structure. A Heap must be a complete tree and satisfy its type’s properties.

Types

Max Heap

The value of the parent node must be greater than its child nodes’ values. Meaning the Root is the largest value in this heap’s tree.

Min Heap

The value of the parent node must be less than its child nodes’ values. Meaning the Root is the smallest value in this heap’s tree.

Heaps and Priority Queues

In some contexts these ae treated the same.

Time complexity

OperationBig-O
Find max/minO(1)
InsertO(log(n))
RemoveO(log(n))
Heapify (create a heap out of given array of elements)O(n)

Techniques

Mention of k

Questions containing “lowest k” or “top k” are often a good signal that a heap can be used to solve. See Top K Frequent Elements.

Example: If you require the Top k elements.

  1. Use a Min Heap of size k.
  2. Iterate through each element, pushing it into the heap. (for python heapq, invert the value before pushing to find the max). // not sure what this means?
  3. Whenever the heap size exceeds k, remove the minimum element, that will guarantee that you have the k largest elements.

Essential questions

Recommended practice questions


References