GeeksforGeeks Medium

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 -1 if the heap is empty.
  • peek(): return the largest value without removing it, or -1 if 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.

Constraints
  • 1 <= number of operations <= 10⁵
  • -10⁹ <= x <= 10⁹
  • pop() and peek() return -1 when the heap is empty
heapdesign
Open on GeeksforGeeks ↗
02

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 i sit at 2i + 1 and 2i + 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.
How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class MaxHeap:
▶2 def __init__(self):
▶3 self.a = []
▶4 
▶5 def push(self, x):
▶6 a = self.a
▶7 a.append(x)
▶8 i = len(a) - 1
▶9 while i > 0:
▶10 parent = (i - 1) // 2
▶11 if a[parent] >= a[i]:
▶12 break
▶13 a[parent], a[i] = a[i], a[parent]
▶14 i = parent
▶15 
▶16 def pop(self):
▶17 a = self.a
▶18 if not a:
▶19 return -1
▶20 top = a[0]
▶21 a[0] = a[-1]
▶22 a.pop()
▶23 i, n = 0, len(a)
▶24 while True:
▶25 big = i
▶26 left, right = 2 * i + 1, 2 * i + 2
▶27 if left < n and a[left] > a[big]:
▶28 big = left
▶29 if right < n and a[right] > a[big]:
▶30 big = right
▶31 if big == i:
▶32 break
▶33 a[i], a[big] = a[big], a[i]
▶34 i = big
▶35 return top
▶36 
▶37 def peek(self):
▶38 return self.a[0] if self.a else -1
▶39 
▶40 def size(self):
▶41 return len(self.a)
arrayemptystart: empty heap
a[]0 values
The heap starts empty. Each value will be appended to the array, and the tree above is just a drawing of that array: index i has its children at 2i + 1 and 2i + 2.
4array40push 4 → root
x4appended
i0the root
The heap was empty, so 4 becomes the root. It has no parent to compare with, so the push is done.
41array4011push 1 → index 1
x1appended
i1parent at 0
Append 1 at index 1, the next free slot, so the tree stays complete. Its parent is index (1 - 1) // 2 = 0, which may now be smaller than it.
41array40114 ≥ 1 → stop
parent4index 0
a[4, 1]
The parent 4 is at least 1, so this pair obeys the rule. Every value above that parent is larger still, so climbing further would change nothing: the push ends here.
417array401172push 7 → index 2
x7appended
i2parent at 0
Append 7 at index 2, the next free slot, so the tree stays complete. Its parent is index (2 - 1) // 2 = 0, which may now be smaller than it.
714array7011427 > 4 → swap up
swapindex 0 ↔ 2
i0reached the root
7 is larger than its parent 4, which breaks the rule, so they swap. 7 is now the root, the largest value in the heap, so the push is done.
7143array70114233push 3 → index 3
x3appended
i3parent at 1
Append 3 at index 3, the next free slot, so the tree stays complete. Its parent is index (3 - 1) // 2 = 1, which may now be smaller than it.
7341array703142133 > 1 → swap up
swapindex 1 ↔ 3
i1keep climbing
3 is larger than its parent 1, which breaks the rule, so they swap. The rule now holds between them, and 3 is compared with its new parent next.
7341array703142137 ≥ 3 → stop
parent7index 0
a[7, 3, 4, 1]
The parent 7 is at least 3, so this pair obeys the rule. Every value above that parent is larger still, so climbing further would change nothing: the push ends here.
73419array7031421394push 9 → index 4
x9appended
i4parent at 1
Append 9 at index 4, the next free slot, so the tree stays complete. Its parent is index (4 - 1) // 2 = 1, which may now be smaller than it.
79413array70914213349 > 3 → swap up
swapindex 1 ↔ 4
i1keep climbing
9 is larger than its parent 3, which breaks the rule, so they swap. The rule now holds between them, and 9 is compared with its new parent next.
97413array90714213349 > 7 → swap up
swapindex 0 ↔ 1
i0reached the root
9 is larger than its parent 7, which breaks the rule, so they swap. 9 is now the root, the largest value in the heap, so the push is done.
97413array9071421334final heap [9, 7, 4, 1, 3]
a[9, 7, 4, 1, 3]
Every parent is now at least as large as its children, so the root 9 is the maximum. The array is not sorted: only each parent versus its own children is ordered.
05

Common pitfalls

Using the 1-based parent formula

✗ Wrong
parent = i // 2
✓ Right
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

✗ Wrong
if left < n and a[left] > a[i]:
    big = left
elif right < n and a[right] > a[i]:
    big = right
✓ Right
if left < n and a[left] > a[big]:
    big = left
if right < n and a[right] > a[big]:
    big = right

Popping [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

✗ Wrong
top = a.pop(0)
✓ Right
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.

06

Edge cases

pop() or peek() on an empty heap

Both check the size before reading a[0] and return -1, so they never index an empty array.

Popping the only value left

The last value is copied onto itself, the array shrinks to empty, and the sift loop finds no children and stops at once.

Equal values

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.

07

Complexity

Time
O(log n) push and pop
Space
O(n)
A heap of n values is ⌊log₂ n⌋ levels deep, and each sift moves one level per swap, so push and pop do at most that many swaps. peek and size are O(1). The array stores exactly the n values, with no pointers.
08

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.