Implement Max Heap
Implement Max Heap is a GFG problem (Medium). Write a max-heap class on a plain array, without a library priority queue. It supports four operations:
push(x): add a value.pop(): remove and return the largest value, or-1if the heap is empty.peek(): return the largest value without removing it, or-1if empty.size(): return how many values are stored.
With up to 10⁵ operations, push and pop must each run in O(log n). Scanning the whole array for the maximum on every pop would be O(n) per call.
- 1 <= number of operations <= 10⁵
- -10⁹ <= x <= 10⁹
- pop() and peek() return -1 when the heap is empty
Intuition
A max-heap is a binary tree with one rule: every parent is at least as large as its children. That puts the largest value at the root. The tree is also kept complete (every level full, the last one filled from the left), so it fits in an array with no gaps:
- Index maths: the children of index
isit at2i + 1and2i + 2, and its parent at(i - 1) // 2. - One path to repair: a push or a pop breaks the rule at a single spot. Swapping that value up or down along one root-to-leaf path (sift up and sift down) fixes it, and a path has only about log₂ n nodes.
Whenever a program keeps asking for the current largest (or smallest) item while new items keep arriving, it needs a heap: task schedulers, top-k lists, merging sorted streams. Writing push and pop by hand is the standard check that you know the array layout and both sift directions.
Approach
Before reading on, take the heap [9, 7, 4, 1, 3] and pop it. Which value moves to the root, which child does it swap with, and where does it stop? Aim for O(log n) per push and pop.
Store the tree in an array
Keep the values in a list a. Index 0 is the root, and the node at index i has children at 2i + 1 and 2i + 2. Filling the array strictly left to right keeps the tree complete, so these formulas always land on the right node and no pointers are needed.
Push: append, then sift up
Append x at the end, the only slot that keeps the tree complete. While x is larger than its parent at (i - 1) // 2, swap them and move i up. Stop at the root, or as soon as the parent is at least as large, because every value above that parent is larger still.
Pop: move the last value to the root
If the array is empty, return -1. Otherwise save a[0], copy the last value into index 0 and shrink the array by one. Taking the last value keeps the tree complete, and now only the root can break the parent rule.
Sift the new root down
Find the larger of the node's two children. If that child is bigger than the node, swap them and continue from the child's index; otherwise stop. Always swap with the larger child: it becomes the parent of the other child as well, so the rule holds on both sides.
Why the heap stays valid
Each swap fixes the one pair it touches and leaves every other parent-child pair as it was. So when a sift stops, the whole tree obeys the rule again, the root holds the maximum, and repeated pops return values in falling order.
Code in Python, C++ and Java
i has its children at 2i + 1 and 2i + 2.(1 - 1) // 2 = 0, which may now be smaller than it.(2 - 1) // 2 = 0, which may now be smaller than it.(3 - 1) // 2 = 1, which may now be smaller than it.(4 - 1) // 2 = 1, which may now be smaller than it.i has its children at 2i + 1 and 2i + 2. Every parent here is at least as large as its children, so the maximum 9 sits at the root.i has its children at 2i + 1 and 2i + 2. Every parent here is at least as large as its children, so the maximum 5 sits at the root.a[0] would fail, so pop checks the size first and returns -1.Common pitfalls
Using the 1-based parent formula
parent = i // 2
parent = (i - 1) // 2
i // 2 is the parent only when the root sits at index 1. With the root at index 0 it points at the wrong node: pushing 9 into [8, 3, 7, 1, 2] ends as [9, 8, 3, 1, 2, 7], where 3 sits above its child 7.
Swapping with the first child that is larger
if left < n and a[left] > a[i]:
big = left
elif right < n and a[right] > a[i]:
big = rightif left < n and a[left] > a[big]:
big = left
if right < n and a[right] > a[big]:
big = rightPopping [10, 5, 8, 1, 2] puts 2 at the root. The wrong version swaps it with 5 because 5 is checked first, giving [5, 2, 8, 1]: 5 now sits above 8, so the next pop returns 5 instead of 8.
Removing the root by shifting the array
top = a.pop(0)
top = a[0] a[0] = a[-1] a.pop() # then sift a[0] down
Shifting costs O(n) and moves every child under a different parent. Popping [9, 2, 8, 1, 1, 7] this way leaves [2, 8, 1, 1, 7], with 2 above 8.
Edge cases
Both check the size before reading a[0] and return -1, so they never index an empty array.
The last value is copied onto itself, the array shrinks to empty, and the sift loop finds no children and stops at once.
Sift-up stops when the parent is >= the new value, so a pushed duplicate is not swapped needlessly. Either way the rule "parent at least as large" still holds.
Complexity
peek and size are O(1). The array stores exactly the n values, with no pointers.Implement Max Heap FAQ
Why does build heap run in O(n), not O(n log n)?
Run sift-down on every non-leaf, from index n // 2 - 1 back to 0. Half the nodes are leaves and never move, a quarter can drop at most one level, an eighth at most two, and so on. That sum stays below n swaps, so building the heap is linear, while n separate pushes can cost O(n log n).
Is the array of a max-heap sorted?
No. [9, 7, 4, 1, 3] is a valid max-heap, yet 1 comes before the larger 3, so it is not in falling order. Only each parent against its own children is ordered. That weaker promise is why a push costs O(log n), while keeping an array fully sorted costs O(n) per insert.
How do you get a max-heap from Python's heapq?
heapq only maintains a min-heap. Push -x instead of x and negate whatever you pop: the smallest negative number is the largest original value.