A heap is a specialized tree-based data structure that satisfies the heap property: in a max-heap, parent nodes are always greater than or equal to their children; in a min-heap, parent nodes are always less than or equal to their children. Heaps are the foundation for priority queues and enable efficient algorithms like heap sort and finding the kth largest element.
Unlike Binary Search Trees, heaps don’t maintain a fully sorted order—they only guarantee the min/max element is at the root. This relaxed ordering enables O(1) access to the min/max and O(log n) insertions and deletions.
Heaps provide O(1) access to the minimum (min-heap) or maximum (max-heap) element and O(log n) insertion and deletion, making them ideal for priority queues and algorithms requiring repeated min/max access.
What is a heap?
A heap is a complete binary tree (all levels filled except possibly the last, which is filled left-to-right) that maintains the heap property:
functionmergeKSortedLists(lists) {
constminHeap=newMinHeap();
constresult= [];
// Insert first element from each list with index tracking
for (leti=0; i<lists.length; i++) {
if (lists[i].length>0) {
minHeap.insert({value:lists[i][0], listIdx:i, elemIdx:0});
}
}
while (!minHeap.isEmpty()) {
const {value, listIdx, elemIdx} =minHeap.extractMin();
result.push(value);
// Add next element from same list
if (elemIdx+1<lists[listIdx].length) {
minHeap.insert({
value:lists[listIdx][elemIdx+1],
listIdx,
elemIdx:elemIdx+1 });
}
}
returnresult;
}
console.log(mergeKSortedLists([[1, 4, 5], [1, 3, 4], [2, 6]]));
// [1, 1, 2, 3, 4, 4, 5, 6]
import heapq
defmerge_k_sorted_lists(lists):
# Python has built-in heapq module heap = []
result = []
# Insert first element from each listfor i, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], i, 0))
while heap:
value, list_idx, elem_idx = heapq.heappop(heap)
result.append(value)
# Add next element from same listif elem_idx +1< len(lists[list_idx]):
heapq.heappush(heap, (
lists[list_idx][elem_idx +1],
list_idx,
elem_idx +1 ))
return result
print(merge_k_sorted_lists([[1, 4, 5], [1, 3, 4], [2, 6]]))
# [1, 1, 2, 3, 4, 4, 5, 6]
import java.util.PriorityQueue;publicstatic List<Integer>mergeKSortedLists(int[][] lists){// Java has built-in PriorityQueue (min-heap)
PriorityQueue<int[]> minHeap =new PriorityQueue<>((a, b)-> a[0]- b[0]// Compare by value
); List<Integer> result =new ArrayList<>();// Insert first element from each list
for(int i = 0; i < lists.length; i++){if(lists[i].length> 0){ minHeap.offer(newint[]{lists[i][0], i, 0});}}while(!minHeap.isEmpty()){int[] curr = minHeap.poll();int value = curr[0], listIdx = curr[1], elemIdx = curr[2]; result.add(value);// Add next element from same list
if(elemIdx + 1 < lists[listIdx].length){ minHeap.offer(newint[]{ lists[listIdx][elemIdx + 1], listIdx, elemIdx + 1
});}}return result;}
Complexity analysis
Operation
Time Complexity
Space Complexity
Insert
O(log n)
O(1)
Extract Min/Max
O(log n)
O(1)
Peek Min/Max
O(1)
O(1)
Build Heap
O(n)
O(n)
Heap Sort
O(n log n)
O(1) in-place
Delete arbitrary
O(log n)
O(1)
Search
O(n)
O(1)
Common pitfalls
Not maintaining complete tree: Heaps must be complete binary trees
Confusing min-heap and max-heap: Know which you need
Off-by-one errors: Array indexing formulas are tricky
Not heapifying after changes: Always restore heap property after modifications
Using heap for searching: Heaps are not for general searching (O(n))
Ugly number II (numbers with only 2, 3, 5 as prime factors)
Sort a nearly sorted (k-sorted) array
Maximum sum of distinct subarrays with length k
Sliding window maximum using heap
Reorganize string so no two adjacent characters are same
Design Twitter feed (combine k user timelines)
Trapping rain water using heaps
Smallest range covering elements from k lists
Find the most competitive subsequence
Complexity summary
Time:
Insert/Delete: O(log n)
Peek: O(1)
Build heap: O(n)
Heap sort: O(n log n)
Space: O(n) for storing n elements
Heaps provide the perfect balance between fully sorted structures (BSTs) and unsorted structures, offering efficient access to the min/max element while maintaining dynamic insertion and deletion.
Thanks for visiting
We are actively updating content to this site. Thanks for visiting! Please bookmark this page and visit again soon.