Skip to main content

๐Ÿ”๏ธ Heap (Priority Queue)

One-line summary: A complete binary tree satisfying the heap property โ€” O(log n) insert and extract-min/max, the engine behind Top-K, median, K-way merge, and scheduling algorithms.


Diagramโ€‹

Heap Overview Heap GIF

Conceptโ€‹

  • Min-heap: parent โ‰ค children โ†’ peek() is minimum.
  • Max-heap: parent โ‰ฅ children โ†’ peek() is maximum.
  • JavaScript has no native heap โ€” simulate with sorted array or use @datastructures-js/priority-queue.

Key operations: insert O(log n), extractMin/Max O(log n), peek O(1), heapify O(n).


Time & Space Complexityโ€‹

OperationTimeSpace
InsertO(log n)O(1)
Extract min/maxO(log n)O(1)
PeekO(1)O(1)
HeapifyO(n)O(1)
Top-K elementsO(n log k)O(k)
K-way merge (n total, k lists)O(n log k)O(k)

Common Patternsโ€‹

Pattern 1 โ€” Top-K Frequent (Min-Heap of size K)โ€‹

function topKFrequent(nums, k) {
const freq = new Map();
for (const n of nums) freq.set(n, (freq.get(n) || 0) + 1);
return [...freq.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, k)
.map(([num]) => num);
}

Pattern 2 โ€” Two Heaps (Median from Stream)โ€‹

// maxHeap = lower half, minHeap = upper half
// Invariant: |maxHeap.size - minHeap.size| <= 1
// Median = maxHeap.top() or avg of both tops

Pattern 3 โ€” K-way Mergeโ€‹

// 1. Add first element from each list to min-heap with [value, listIdx, elemIdx]
// 2. Extract min โ†’ push to result โ†’ add next element from same list
// 3. Repeat until heap empty

Pitfallsโ€‹

  • JS has no native heap โ€” off-the-shelf sort trick is O(n log n), not O(n log k)
  • Rebalancing Two Heaps: ensure size diff โ‰ค 1 after every insert
  • K-way merge: track which list each heap element came from

Practice Problemsโ€‹

ProblemDifficultySolution
LC 215 โ€” Kth Largest ElementMediumView Solution
LC 973 โ€” K Closest Points to OriginMedium
LC 295 โ€” Find Median from Data StreamHard
LC 23 โ€” Merge K Sorted ListsHard
LC 378 โ€” Kth Smallest in Sorted MatrixMedium
LC 373 โ€” Find K Pairs with Smallest SumsMedium
LC 480 โ€” Sliding Window MedianHard
LC 502 โ€” IPOHard
LC 703 โ€” Kth Largest Element in a StreamEasy
CC โ€” IPC Trainers (IPCTRAIN)Hard
LC 1046 โ€” Last Stone WeightEasy
LC 1337 โ€” The K Weakest Rows in a MatrixEasy
LC 1464 โ€” Maximum Product of Two Elements in an ArrayEasy
LC 1845 โ€” Seat Reservation ManagerMedium
LC 347 โ€” Top K Frequent ElementsMedium
LC 692 โ€” Top K Frequent WordsMedium
LC 1167 โ€” Minimum Cost to Connect SticksMedium
LC 1353 โ€” Maximum Number of Events That Can Be AttendedMedium
LC 1642 โ€” Furthest Building You Can ReachMedium
LC 1834 โ€” Single-Threaded CPUMedium
LC 2542 โ€” Maximum Subsequence ScoreMedium
CC โ€” Heap Operations (HEAPOPS)Medium
CC โ€” Priority Queue (PRIORQUE)Medium
LC 218 โ€” The Skyline ProblemHard
LC 239 โ€” Sliding Window MaximumHard
LC 407 โ€” Trapping Rain Water IIHard
LC 632 โ€” Smallest Range Covering Elements from K ListsHard
LC 857 โ€” Minimum Cost to Hire K WorkersHard
LC 1439 โ€” Find the Kth Smallest Sum of a Matrix With Sorted RowsHard
LC 2386 โ€” Find the K-Sum of an ArrayHard
CC โ€” Advanced Heap (ADVHEAP)Hard

  • Trees โ€” heap is a complete binary tree
  • Sorting โ€” heapsort uses heap operations
  • Graphs โ€” Dijkstra uses min-heap

Heap Data Structure Referenceโ€‹

The following notes and runnable implementations (with tests) live alongside this guide in this folder.

In computer science, a heap is a specialized tree-based data structure that satisfies the heap property described below.

In a min heap, if P is a parent node of C, then the key (the value) of P is less than or equal to the key of C.

MinHeap

In a max heap, the key of P is greater than or equal to the key of C.

MaxHeap

Array Representation

The node at the "top" of the heap with no parents is called the root node.

Time Complexitiesโ€‹

Here are time complexities of various heap data structures. Function names assume a max-heap.

Operationfind-maxdelete-maxinsertincrease-keymeld
Binaryฮ˜(1)ฮ˜(log n)O(log n)O(log n)ฮ˜(n)
Leftistฮ˜(1)ฮ˜(log n)ฮ˜(log n)O(log n)ฮ˜(log n)
Binomialฮ˜(1)ฮ˜(log n)ฮ˜(1)O(log n)O(log n)
Fibonacciฮ˜(1)ฮ˜(log n)ฮ˜(1)ฮ˜(1)ฮ˜(1)
Pairingฮ˜(1)ฮ˜(log n)ฮ˜(1)o(log n)ฮ˜(1)
Brodalฮ˜(1)ฮ˜(log n)ฮ˜(1)ฮ˜(1)ฮ˜(1)

Where:

  • find-max (or find-min): find a maximum item of a max-heap, or a minimum item of a min-heap, respectively (a.k.a. peek)
  • delete-max (or delete-min): removing the root node of a max heap (or min heap), respectively
  • insert: adding a new key to the heap (a.k.a., push)
  • increase-key or decrease-key: updating a key within a max- or min-heap, respectively
  • meld: joining two heaps to form a valid new heap containing all the elements of both, destroying the original heaps.

In this repository, the MaxHeap.js and MinHeap.js are examples of the Binary heap.

Implementationโ€‹

Referencesโ€‹

โ† Back to Home ยท ยฉ sparshjaswal