Trusted answers to developer questions

Min Heap vs. Max Heap

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Min and Max heaps are complete binary trees with some unique properties.

Binary Tree

A Binary Tree is a tree data structure wherein each node has at most two “children.”

A node in the binary tree typically contains the following properties:

  • Reference to the left child.
  • Reference to the right child.
  • Data

A complete Binary Tree is a binary tree in which every level, except possibly the last, is filled.

svg viewer

Min-Heap

  • The root node has the minimum value.

  • The value of each node is equal to or greater than the value of its parent node.

  • A complete binary tree.

Max-Heap

  • The root node has the maximum value.

  • The value of each node is equal to or less than the value of its parent node.

  • A complete binary tree.

svg viewer

How are Min/Max Heaps represented?

A Min/Max heap is typically represented as an array.

  • Arr[0] Returns the root node.
  • Arr[(i-1)/2] Returns the parent node.
  • Arr[(2*i)+1] Returns the left child node.
  • Arr[(2*i)+2] Returns the right child node.

Time Complexity of Min/Max Heap

svg viewer
  • Get Max or Min Element

    • The Time Complexity of this operation is O(1).
  • Remove Max or Min Element

    • The time complexity of this operation is O(Log n) because we need to maintain the max/mix at their root node, which takes Log n operations.
  • Insert an Element

    • Time Complexity of this operation is O(Log n) because we insert the value at the end of the tree and traverse up to remove violated property of min/max heap.

RELATED TAGS

binary trees
heap
data structures
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?