Complete binary tree (add leaf element at left most) that satistify heap property (for all nodes either parent >= child or parent <= child).
Two types of heap: Min-heap (root/heap[0] is smallest) and Max-heap (root/heap[0] is largest)
For array representation of heap tree, for every node at index i
in array:
- index of left child is given by
2i + 1
and the right child is given by2i + 2
- parent of
i
is given by(i - 1) / 2
1. Raw Implimentation: https://www.programiz.com/dsa/heap-data-structure
heapq in python: follow zero based indexing and implements min-heap
heap[0]
is the smallest itemheap.sort()
maintains the heap invariant!
Basic Functions:
heapq.heapify(list)
- O(n) in an array. Each individual call to heapify can take O(logn).heapq.heappush
(heap, item) - O(log n)heapq.heappop
(heap) - O(log n) - returns smallestheapq.nlargest
(n, iterable, key=None)heapq.nsmallest
(n, iterable, key=None)
---
heapq impliments MinHeap by default, to impliment MaxHeap:
class MaxHeap:
def __init__(self, array = []):
self.heap = array
self.heapify()
def heapify(self):
self.heap = list(map(lambda x: -x, self.heap))
heapq.heapify(self.heap)
def push(self, item):
heapq.heappush(self.heap, -item)
def pop(self): # returns largest
popped = heapq.heappop(self.heap)
return -popped
def length(self):
return len(self.heap)
heapq
documentation: https://docs.python.org/3/library/heapq.html