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

← Back to Home Β· Β© sparshjaswal