MODULE 4.6: PRIORITY QUEUE — URGENCY FIRST & HEAPS

A student-friendly guide to Priority Queues—how serving the most urgent item first differs from a regular line, why binary heaps are used to build them, and where they show up in real apps.

💡 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.

1. Building a Priority Queue with a Heap & Comparing Options
In a 0-based array heap, any item at index i has a parent at (i - 1) / 2 and children at 2 * i + 1 and 2 * i + 2:
  • Min-Priority (Smallest Number Wins): Priority 1 is more urgent than priority 3—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)
C++ (min_heap_priority_queue.cpp)
#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;
}
Output: [Priority 1] Executing: Database Failover Alert [Priority 2] Executing: Process Payment Webhook [Priority 3] Executing: Send Weekly Newsletter
2. Shortest Paths (Dijkstra) & Top-K Items
Two classic algorithms you'll see in courses and coding practice use a priority queue to pick the best candidate next:
  • 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 K lets you track the top K numbers without sorting the entire dataset.
Python (dijkstra_and_topk_heap.py)
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))
Output: Shortest distances from Pune: {'Pune': 0, 'Lonavala': 65, 'Satara': 115, 'Mumbai': 148, 'Kolhapur': 237} Top-3 Latency Spikes (ms): [310, 275, 185]
3. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Here are five real-world situations where urgency matters more than who arrived first:
  • 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.
Python (realtime_pq_apps_1_to_5.py)
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()
Output: [Triage Level 1] Treating Ananya (Severe Chest Pain) [Triage Level 1] Treating Meera (Acute Asthma Attack) [Triage Level 2] Treating Vikram (Deep Laceration) [Triage Level 3] Treating Ramesh (Mild Fever)
4. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-world places where priority queues help programs choose what comes 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.
Python (realtime_pq_apps_6_to_10.py)
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))
Output: Step 1: Merged 'A'(5) + 'B'(9) -> weight 14 Step 2: Merged 'C'(12) + 'D'(13) -> weight 25 Step 3: Merged '(A+B)'(14) + 'E'(16) -> weight 30 Step 4: Merged '(C+D)'(25) + '((A+B)+E)'(30) -> weight 55 Step 5: Merged 'F'(45) + '((C+D)+((A+B)+E))'(55) -> weight 100 6. Huffman Root: (100, '(F+((C+D)+((A+B)+E)))')
5. Exam & Study Tips for Students
Keep these three reminders in mind when writing heap code or answering exam questions:
  • Add a tie-breaker number when storing objects: If two items have the same priority, Python's heapq will 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.
Python (priority_queue_checklist.py)
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)
Output: * 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.