Skip to main content
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
2 ≤ 52 ≤ 85 ≤ 125 ≤ 98 ≤ 15Root: 2 (…5 [idx 1]8 [idx 2]12 [idx 3]9 [idx 4]15 [idx 5]
ROOTRoot: 2 (Min)
2 links
Quick 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, and O(N) bottom-up heapify.

Practical Takeaways

  • Top-K streaming queries: Keep a size-K min-heap to find the largest K elements in O(N log K) time and O(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.