Skip to content

Latest commit

 

History

History
60 lines (39 loc) · 1.8 KB

heaps.md

File metadata and controls

60 lines (39 loc) · 1.8 KB

Heaps

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 by 2i + 2
  • parent of i is given by (i - 1) / 2

2. Implimentation using heapq

heapq in python: follow zero based indexing and implements min-heap

  • heap[0] is the smallest item
  • heap.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 smallest
  • heapq.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)

Resources