What is a Priority Queue?
A priority queue throws out the "first come, first served" rule that a normal queue follows. Every element carries a priority, and whichever element has the most urgent priority gets dequeued next — it doesn't matter how long it's been sitting there.
Key Characteristics
Priority queues have these fundamental properties:
- Priority-based ordering:
- Elements are processed by priority (highest first or lowest first)
- Two core operations:
- insert(item, priority) - Add with priority
- extractMax()/extractMin() - Remove highest/lowest priority item
- Peek operation:
- View highest/lowest priority item without removal
- No FIFO guarantee:
- Equal priority elements may be processed in arbitrary order
Implementation Variations
Common implementation approaches:
- Binary Heap:
- Most common implementation
- O(log n) insert and extract
- O(1) peek
- Memory efficient
- Balanced Binary Search Tree:
- O(log n) all operations
- Supports more operations (like delete-by-value)
- Higher memory overhead
- Array (Unsorted):
- O(1) insert, O(n) extract
- Simple but inefficient for large datasets
- Fibonacci Heap:
- Amortized O(1) insert
- O(log n) extract
- Complex implementation
Applications
Priority queues are used in:
- Dijkstra's Algorithm: Finding shortest paths in graphs
- Huffman Coding: Data compression
- Operating Systems: Process scheduling
- Event-driven Simulation: Processing events in time order
- A* Search: Pathfinding in AI
- Bandwidth Management: Prioritizing network packets
Special Cases
Interesting priority queue variations:
- Min-Priority Queue: Extracts minimum priority first
- Max-Priority Queue: Extracts maximum priority first
- Double-Ended Priority Queue: Supports both min and max extraction
- Indexed Priority Queue: Allows priority updates by key
- Bounded Priority Queue: Fixed capacity with eviction policies
What makes it so useful is that it always hands you the most important item on demand, which is exactly what a lot of algorithms need. Under the hood it's usually built on a heap, though a balanced BST works too — which one you pick depends on how the application balances insertion speed against extraction speed.