Heaps and Priority Queues

November 19, 2025
#heap #priority-queue #min-heap #max-heap #data-structures #algorithms #interviewing

Introduction

A heap is a specialized tree-based data structure that satisfies the heap property: in a max-heap, parent nodes are always greater than or equal to their children; in a min-heap, parent nodes are always less than or equal to their children. Heaps are the foundation for priority queues and enable efficient algorithms like heap sort and finding the kth largest element.

Unlike Binary Search Trees, heaps don’t maintain a fully sorted order—they only guarantee the min/max element is at the root. This relaxed ordering enables O(1) access to the min/max and O(log n) insertions and deletions.

Review Binary Trees, Arrays, and Big-O Notation first if needed.

What is a heap?

A heap is a complete binary tree (all levels filled except possibly the last, which is filled left-to-right) that maintains the heap property:

Min-Heap Property

Every parent node ≤ its children

       1
      / \
     3   2
    / \ / \
   7  5 4  6

Root (1) is the minimum element.

Max-Heap Property

Every parent node ≥ its children

      10
      / \
     7   9
    / \ / \
   3  5 4  8

Root (10) is the maximum element.

Why use a heap?

Choose a heap when:

  1. You need repeated access to min/max element
  2. You’re implementing a priority queue
  3. You need heap sort (in-place, O(n log n))
  4. You’re finding the kth largest/smallest element
  5. You’re merging k sorted lists
  6. You need efficient median tracking in a stream
  7. You’re implementing Dijkstra’s shortest path algorithm

Avoid a heap when:

  • You need arbitrary access to elements (use array)
  • You need full sorting (use sorting algorithms or BST)
  • You need FIFO order (use queue)
  • You need O(1) lookup by key (use hash table)

Real-world applications

Heaps are used extensively:

  • Operating systems: CPU task scheduling (priority queues)
  • Dijkstra’s algorithm: Finding shortest paths in graphs
  • Event-driven simulation: Processing events by priority/time
  • Data compression: Huffman coding uses min-heaps
  • Load balancing: Distributing tasks by priority
  • A pathfinding*: Managing open set in game AI
  • K-way merge: Merging multiple sorted streams
  • Real-time systems: Managing tasks by deadline

Heap representation

Heaps are typically implemented using arrays (not pointers) for efficiency:

Array: [10, 7, 9, 3, 5, 4, 8]
Index:  0  1  2  3  4  5  6

Visualized as tree:
      10
      / \
     7   9
    / \ / \
   3  5 4  8

Array indexing formulas (0-indexed):

  • Parent of node at index i: (i - 1) / 2
  • Left child of node at index i: 2 * i + 1
  • Right child of node at index i: 2 * i + 2

Alternative (1-indexed):

  • Parent: i / 2
  • Left child: 2 * i
  • Right child: 2 * i + 1

Heap operations

Heapify (Bubble Down)

After removing the root or violating the heap property, restore it by moving elements down.

Bubble Up

After insertion, restore heap property by moving the element up.

Min-Heap implementation

Building a heap from an array

Instead of inserting elements one by one (O(n log n)), we can build a heap in O(n) using heapify:

Heap sort

Use a heap to sort an array in O(n log n) time:

Common heap problems

Find kth largest element

Merge k sorted lists

Complexity analysis

Operation Time Complexity Space Complexity
Insert O(log n) O(1)
Extract Min/Max O(log n) O(1)
Peek Min/Max O(1) O(1)
Build Heap O(n) O(n)
Heap Sort O(n log n) O(1) in-place
Delete arbitrary O(log n) O(1)
Search O(n) O(1)

Common pitfalls

  • Not maintaining complete tree: Heaps must be complete binary trees
  • Confusing min-heap and max-heap: Know which you need
  • Off-by-one errors: Array indexing formulas are tricky
  • Not heapifying after changes: Always restore heap property after modifications
  • Using heap for searching: Heaps are not for general searching (O(n))

When to prefer other data structures

  • Need full sorting → Use sorting algorithms
  • Need O(1) arbitrary access → Use array
  • Need O(1) key lookup → Use hash table
  • Need ordered traversal → Use BST
  • Need FIFO → Use queue

Practice problems

  1. Find the kth smallest element in an array
  2. Find median from data stream
  3. Merge k sorted arrays
  4. Top K frequent elements
  5. Find K closest points to origin
  6. Task scheduler with cooldown periods
  7. Ugly number II (numbers with only 2, 3, 5 as prime factors)
  8. Sort a nearly sorted (k-sorted) array
  9. Maximum sum of distinct subarrays with length k
  10. Sliding window maximum using heap
  11. Reorganize string so no two adjacent characters are same
  12. Design Twitter feed (combine k user timelines)
  13. Trapping rain water using heaps
  14. Smallest range covering elements from k lists
  15. Find the most competitive subsequence

Complexity summary

  • Time:
    • Insert/Delete: O(log n)
    • Peek: O(1)
    • Build heap: O(n)
    • Heap sort: O(n log n)
  • Space: O(n) for storing n elements

Heaps provide the perfect balance between fully sorted structures (BSTs) and unsorted structures, offering efficient access to the min/max element while maintaining dynamic insertion and deletion.

Thanks for visiting
We are actively updating content to this site. Thanks for visiting! Please bookmark this page and visit again soon.
Sponsor