CSData StructuresDiagramBeginner
Heap & Priority Queue
KO: 힙 & 우선순위 큐·EN: Heap & Priority Queue·JA: ヒープ&優先度付きキュー
A complete binary tree stored in an array that peeks the highest-priority element in O(1) and supports O(log N) insertion and extraction
Table of Contents
Structure Diagram
Min-Heap Priority Queue Tree StructureTap a node
ROOTRoot: 2 (Min)
2 linksQuick Answer
What is Heap & Priority Queue?
A complete binary tree stored in an array that peeks the highest-priority element in O(1) and supports O(log N) insertion and extraction. It is a core concept in Data Structures within CS.
Core Principles
A Priority Queue serves elements by priority rather than arrival order, and is most commonly implemented using a Binary Heap.
- Heap Property: In a Min-Heap every parent is
≤its children (Max-Heap:≥), guaranteeing the highest-priority item sits at the root. - Array Representation: Because a binary heap is a complete binary tree, parent (
(i-1)/2) and children (2i+1,2i+2) map directly to array indices with zero pointer overhead. - Complexity:
O(1)peek,O(log N)push/pop via sift-up/sift-down, andO(N)bottom-up heapify.
Practical Takeaways
- Top-K streaming queries: Keep a size-
Kmin-heap to find the largestKelements inO(N log K)time andO(K)memory instead of sorting everything. - Handling priority updates: Heaps don't support fast arbitrary lookups (
O(N)). Use lazy deletion (pushing updated duplicates and skipping stale entries on pop) or an indexed heap. - Do not confuse with Heap Memory: The data structure Binary Heap is unrelated to the dynamic memory allocation heap.
Notable Examples
- Dijkstra & A Pathfinding*: Popping the next closest unvisited vertex in
O(log V). - Job & Timer Schedulers: Pulling the next due task by timestamp in runtimes and cron systems.
- K-Way Merge: Merging sorted SSTables in LSM-Tree databases or distributed query shards.