54

A heap is a complete binary tree stored in an array. Max-heap: parent ≥ children (largest on top). Min-heap: parent ≤ children.

Insert and remove-top are O(log n), reading the top is O(1). Building a heap from n items is O(n). Used in heap sort, Dijkstra, scheduling, top-K problems.

The same heap as a tree and as an array

The same heap as a tree and as an array

C++ 6 lines
priority_queue<int> maxHeap;                              // largest on top
priority_queue<int, vector<int>, greater<int>> minHeap;   // smallest on top

for (int x : {5, 1, 8, 3}) { maxHeap.push(x); minHeap.push(x); }
cout << maxHeap.top();   // 8
cout << minHeap.top();   // 1