💡 Summary: Helping the Most Urgent Item First Instead of Who Arrived First
In a regular queue, whoever gets in line first gets served first. A Priority Queue changes that rule: each item has a priority (like urgency, importance, or cost), and whichever item has the top priority gets picked next.
While you could build a priority queue using a plain list or array, a Binary Heap is usually the best fit because it keeps the top-priority item right at the front to peek at in O(1) time while adding and removing items in O(log n) time. That's why priority queues power shortest-path routing, task schedulers, and emergency triage systems.
i has a parent at (i - 1) / 2 and children at 2 * i + 1 and 2 * i + 2:
- Min-Priority (Smallest Number Wins): Priority
1is more urgent than priority3—great for shortest distances, earliest deadlines, or severity levels where 1 is highest. - Max-Priority (Largest Number Wins): Larger numbers come first—great when the biggest score, bid, or reward should go next.
| How You Build It | insert() |
Remove Top | Peek Top |
|---|---|---|---|
| Unsorted Array / List | O(1) | O(n) (have to scan for top priority) | O(n) |
| Sorted Array / List | O(n) (have to find spot / shift) | O(1) | O(1) |
| Binary Heap (Most Common) | O(log n) | O(log n) | O(1) |
#include
#include
#include
using namespace std;
class MinPriorityQueue {
private:
vector> heap; // {priority_number, task_name} (smaller = higher urgency)
void siftUp(int idx) {
while (idx > 0) {
int parent = (idx - 1) / 2;
if (heap[idx].first < heap[parent].first) {
swap(heap[idx], heap[parent]);
idx = parent;
} else {
break;
}
}
}
void siftDown(int idx) {
int n = heap.size();
while (true) {
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < n && heap[left].first < heap[smallest].first) smallest = left;
if (right < n && heap[right].first < heap[smallest].first) smallest = right;
if (smallest != idx) {
swap(heap[idx], heap[smallest]);
idx = smallest;
} else {
break;
}
}
}
public:
bool isEmpty() const { return heap.empty(); }
void push(int priority, const string& task) {
heap.push_back({priority, task});
siftUp(heap.size() - 1);
}
pair pop() {
pair top = heap[0];
heap[0] = heap.back();
heap.pop_back();
if (!heap.empty()) siftDown(0);
return top;
}
};
int main() {
MinPriorityQueue pq;
pq.push(3, "Send Weekly Newsletter");
pq.push(1, "Database Failover Alert");
pq.push(2, "Process Payment Webhook");
while (!pq.isEmpty()) {
auto job = pq.pop();
cout << "[Priority " << job.first << "] Executing: " << job.second << "\n";
}
return 0;
}
- Dijkstra's Shortest Path: Always picks the unvisited place with the smallest distance so far and checks if going through it shortens paths to nearby places.
- Finding the Top-K Biggest Values: Keeping a small Min-Heap of size
Klets you track the topKnumbers without sorting the entire dataset.
import heapq
def dijkstra_shortest_paths(graph, source):
dist = {node: float('inf') for node in graph}
dist[source] = 0
pq = [(0, source)] # (total_distance_so_far, place)
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue # Skip older, longer path entries
for v, weight in graph[u]:
if dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
heapq.heappush(pq, (dist[v], v))
return dist
city_roads = {
"Pune": [("Lonavala", 65), ("Satara", 115)],
"Lonavala": [("Mumbai", 83), ("Satara", 170)],
"Satara": [("Kolhapur", 122)],
"Mumbai": [],
"Kolhapur": []
}
print("Shortest distances from Pune:", dijkstra_shortest_paths(city_roads, "Pune"))
# Top-3 highest latency values using heapq.nlargest
latencies_ms = [42, 185, 19, 310, 88, 275, 64]
print("Top-3 Latency Spikes (ms):", heapq.nlargest(3, latencies_ms))
- 1. Hospital Emergency Room Triage: Urgent emergencies get seen ahead of minor checkups, while patients with the same urgency can be treated in arrival order.
- 2. Map & Route Navigation: Apps explore the closest/fastest next step first to find short routes quickly.
- 3. Important Tasks Before Background Work: An operating system or app can run urgent tasks before low-priority background jobs.
- 4. Real-Time Calls vs. Bulk Downloads: Time-sensitive traffic like voice or video gets priority over slower background transfers.
- 5. Matching Top Bids or Offers: Markets often look for the highest buy price or lowest sell price right away.
import heapq
# 1. Emergency triage where lower severity number = more urgent
# Using arrival_seq breaks ties in arrival order (FIFO for same level)
class HospitalTriage:
def __init__(self):
self.heap = []
self.arrival_seq = 0
def admit_patient(self, severity, name, condition):
heapq.heappush(self.heap, (severity, self.arrival_seq, name, condition))
self.arrival_seq += 1
def treat_next(self):
if not self.heap:
return
sev, seq, name, cond = heapq.heappop(self.heap)
print(f"[Triage Level {sev}] Treating {name} ({cond})")
er = HospitalTriage()
er.admit_patient(3, "Ramesh", "Mild Fever")
er.admit_patient(1, "Ananya", "Severe Chest Pain")
er.admit_patient(2, "Vikram", "Deep Laceration")
er.admit_patient(1, "Meera", "Acute Asthma Attack")
while er.heap:
er.treat_next()
- 6. Huffman Coding (Data Compression): Repeatedly combines the two smallest frequencies first to build compact codes.
- 7. Handling Critical Alerts First: Critical system alerts get attention ahead of routine notifications.
- 8. Running Scheduled Events by Earliest Time: Keeps upcoming events ordered by whichever one happens soonest.
- 9. Combining Multiple Sorted Lists: Picks the smallest current item across several sorted lists cleanly.
- 10. Picking the Closest Driver or Option: Ranks choices by distance or wait time so the nearest match comes up first.
import heapq
# 6. Combining smallest frequency pairs first (Huffman tree idea)
def build_huffman_root_weight(char_freqs):
heap = [(freq, ch) for ch, freq in char_freqs.items()]
heapq.heapify(heap)
step = 1
while len(heap) > 1:
f1, left = heapq.heappop(heap)
f2, right = heapq.heappop(heap)
merged_node = f"({left}+{right})"
heapq.heappush(heap, (f1 + f2, merged_node))
print(f"Step {step}: Merged '{left}'({f1}) + '{right}'({f2}) -> weight {f1 + f2}")
step += 1
return heap[0]
frequencies = {'A': 5, 'B': 9, 'C': 12, 'D': 13, 'E': 16, 'F': 45}
print("6. Huffman Root:", build_huffman_root_weight(frequencies))
- Add a tie-breaker number when storing objects: If two items have the same priority, Python's
heapqwill try to compare the next item in the tuple—adding a unique counter (sequence_id) avoids comparison errors and keeps equal-priority items in arrival order. - Watch out for starvation: If high-priority items keep arriving non-stop, low-priority items could wait forever unless their priority gradually improves over time (called aging).
- Remember: A priority queue is a rule (top priority first), and a binary heap is the most common way to build it fast.
checkpoints = [
"Priority Queue Rule: Always pick the highest-priority item next, not just the oldest.",
"Heap Speed: Peek takes O(1); push and pop take O(log n).",
"Tie-Breaker Tip: Include a counter in (priority, seq, item) so equal priorities don't clash."
]
for item in checkpoints:
print("*", item)