What is a Priority Queue?
A Priority Queue is an abstract data type where each element has a priority value, and elements are served based on priority rather than insertion order. Unlike a standard queue (FIFO), higher-priority elements are dequeued before lower-priority ones, regardless of when they were added.
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
Visual Example (Max-Heap Priority Queue)
Operation sequence:
- insert("A", 3): [(A,3)]
- insert("B", 5): [(A,3), (B,5)] → [(B,5), (A,3)]
- insert("C", 1): [(B,5), (A,3), (C,1)]
- extractMax(): Returns "B" → [(A,3), (C,1)]
- insert("D", 4): [(A,3), (C,1), (D,4)] → [(D,4), (A,3), (C,1)]
- extractMax(): Returns "D" → [(A,3), (C,1)]
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
Time Complexity
- insert(): O(log n) (heap), O(1) amortized (Fibonacci heap)
- extractMax()/extractMin(): O(log n)
- peek(): O(1)
- delete(item): O(log n) (heap), O(1) amortized (Fibonacci heap)
- changePriority(): O(log n)
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
The priority queue is a fundamental data structure that enables efficient management of elements based on their importance or urgency. Its ability to always provide access to the highest (or lowest) priority item makes it indispensable in algorithms where processing order significantly impacts performance or correctness. The choice of implementation (heap, BST, etc.) depends on the specific application's requirements for insertion, extraction, and auxiliary operations.