Im new to heaps, and trying to understand how heaps work. How do you find out the maximum value in a min heap? i understand that the minimum value could be found by looking for the root, but what about the max value in a min heap? not looking for code, more for theory and for my understanding.
3 Answers
Its very easy to point out the maximum value in a min-heap if its illustrated. In a min-heap, the maximum value will always be located near the bottom section of the tree, due to the rules of the min-heap. Where the parent node is a smaller value than that of its children. Therefore its very important to remember that the maximum value will not have any children because of this.
Lets say you are given a min-heap.
2
3 7
6 4 10 15
12 14 9 8
In this min-heap just by looking its very obvious that 15 is the maximum value, since you only have to look at elements 12, 14, 9, 8, 15 that have no children and are in a min-heap.

- 21
- 2
-
Good point! Knowing that the maximum number will necessarily be a leaf node, you can simply iterate through all the leaves and check which one is the greatest. For a heap of n elements, there are n/2 leaves [round up]. The first leaf-node is at index (n/2+1) [round_down], if your indices go from 1 to n, and of course the last leaf is at index n. So iterating from (n/2+1) to n, looking for the greatest should give you the max. It comes out as O(n/2) which is O(n), worst than O(logn), but at least you know you have this too. – ribbit Oct 07 '17 at 04:23
This is just a trick and maybe a little longer than what you need, but if your heap contains numbers you could do this:
- Negate the numbers from the original heap
- Run a Min-Heapify on those. This will cause the smallest number (bigger when negated again) to rise up to the root.

- 1,183
- 11
- 14
-
Negating all the numbers is O(n), so your solution is not more efficient than scanning the leaves, but it's a nice trick – limido Dec 21 '20 at 14:19
The purpose of min-heap is to let you find the minimum element in O(1) time (followed by O(Log n) of heapifying the rest of the heap). Finding both min and max in O(1) is possible, but by using augmented data structures only.
However, if you insist on finding the max element in a min-heap, you can do that by extracting all the elements of the min-heap. The last element extracted from that min-heap would be the max element. The time taken to get he max element would be upper bounded by O(n*Log n). This time complexity is easily derivable - simply Log n summed total n times,

- 13,888
- 8
- 60
- 75
-
1Finding both min and max in O(1) is trivial if you implement a [min-max heap](https://en.wikipedia.org/wiki/Min-max_heap). I suppose you could classify that as an "augmented data structure." All operations on a min-max heap have the same asymptotic complexity as those on a min heap (or max heap), but with a somewhat higher constant. – Jim Mischel Oct 07 '17 at 13:46