What is a Heap?
A heap is a complete binary tree that satisfies the heap property:
Min-Heap: Parent is always smaller than or equal to children. Root is the minimum.
Max-Heap: Parent is always larger than or equal to children. Root is the maximum.
Heaps are typically stored as arrays:
- •Parent of node at index i: (i-1)/2
- •Left child: 2i + 1
- •Right child: 2i + 2
Key operations:
- •Insert (push): O(log n) - add at end, bubble up
- •Extract min/max (pop): O(log n) - remove root, bubble down
- •Peek: O(1) - just return root
In Java, PriorityQueue is a min-heap by default. For max-heap, use Collections.reverseOrder() or negate values.