DSAVisualiseData Structures & Algorithms Studio
Chapter 05 · priority-queue

Priority Queues

Priority Queues maintain dynamic access to extreme elements (min or max). Binary heaps organize elements in complete binary trees backed by compact 1-based or 0-based arrays, where child-parent indices are arithmetic. Median maintenance couples a max-heap and min-heap in balance.

Key Invariants & Rules

  • In a min-heap, parent key <= child key for every node; root holds the global minimum.
  • Complete binary tree invariant: all levels are full except possibly the last, which fills left-to-right.
  • Array indexing (1-based): left child = 2i, right child = 2i+1, parent = floor(i/2).
  • Dual-heap median: max-heap holds smaller half, min-heap holds larger half; sizes differ by at most 1.
  • Swim restores heap order upward by exchanging with parent; sink restores downward by exchanging with smaller child.

Must-Know Algorithms

Binary Heap Push/PopO(log N) push and delMin, O(1) min

Array-backed complete tree providing optimal priority extraction without pointers.

Dual-Heap Median MaintenanceO(log N) insert, O(1) median

Balances lower max-heap and upper min-heap to surface running median.

Ternary HeapO(log₃ N) height, 3 child comparisons

Flatter tree reducing height at the cost of more child comparisons per sink.

Learning Path (5 Lessons)

Self-Check & Concept Review

1. In a 1-based array implementation of a binary heap, where is the parent of element at index k?

1-based indexing maps the parent of node k to integer division k / 2.

2. How does dual-heap median maintenance guarantee O(1) median lookup?

By keeping the smaller half in a max-heap and larger half in a min-heap with size difference <= 1, the median is always at the root of the larger heap.

3. What is the maximum number of children for a node in a Ternary Heap?

A ternary heap is a 3-ary tree where each internal node has up to 3 children.

4. Why does bottom-up heapify on an arbitrary array of N elements run in O(N) linear time rather than O(N log N)?

The sum of heights over all nodes is bounded by N ∑(h/2^h) = 2N = O(N).

5. What invariant distinguishes a Min-Max Heap from a standard Binary Heap?

Min-max heaps alternate min and max levels, allowing both findMin (root) and findMax (level 1) in O(1) time.