0
0
DSA Pythonprogramming

Priority Queue Introduction and Concept in DSA Python

Choose your learning style9 modes available
Mental Model
A priority queue is like a line where people with higher importance get served first, no matter when they arrive.
Analogy: Imagine a hospital emergency room where patients with more serious conditions are treated before others, even if they arrived later.
Priority Queue:
[10] -> [5] -> [3] -> [1] -> null
↑ front (highest priority)
Dry Run Walkthrough
Input: Insert values 3, 10, 5 into an empty priority queue (higher number means higher priority). Then remove the highest priority element.
Goal: Show how elements are added and removed so that the highest priority is always served first.
Step 1: Insert 3 into empty queue
[3] -> null ↑ front
Why: First element becomes the front as it is the only one
Step 2: Insert 10, which has higher priority than 3
[10] -> [3] -> null ↑ front
Why: 10 goes before 3 because it has higher priority
Step 3: Insert 5, which has priority between 10 and 3
[10] -> [5] -> [3] -> null ↑ front
Why: 5 is placed between 10 and 3 to keep order by priority
Step 4: Remove element from front (highest priority)
[5] -> [3] -> null ↑ front
Why: 10 is removed because it has the highest priority
Result:
[5] -> [3] -> null ↑ front
Removed element: 10
Annotated Code
DSA Python
class Node:
    def __init__(self, value, priority):
        self.value = value
        self.priority = priority
        self.next = None

class PriorityQueue:
    def __init__(self):
        self.front = None

    def insert(self, value, priority):
        new_node = Node(value, priority)
        if self.front is None or priority > self.front.priority:
            new_node.next = self.front
            self.front = new_node
            return
        current = self.front
        while current.next and current.next.priority >= priority:
            current = current.next
        new_node.next = current.next
        current.next = new_node

    def remove(self):
        if self.front is None:
            return None
        removed_value = self.front.value
        self.front = self.front.next
        return removed_value

    def __str__(self):
        result = []
        current = self.front
        while current:
            result.append(str(current.value))
            current = current.next
        return ' -> '.join(result) + ' -> null'

# Driver code
pq = PriorityQueue()
pq.insert(3, 3)
pq.insert(10, 10)
pq.insert(5, 5)
print(pq)
removed = pq.remove()
print(pq)
print(f'Removed element: {removed}')
if self.front is None or priority > self.front.priority:
Check if new node should be front because queue is empty or new priority is highest
while current.next and current.next.priority >= priority:
Traverse to find correct position to insert new node maintaining priority order
removed_value = self.front.value
Store value of front node to return after removal
self.front = self.front.next
Remove front node by moving front pointer to next node
OutputSuccess
10 -> 5 -> 3 -> null 5 -> 3 -> null Removed element: 10
Complexity Analysis
Time: O(n) because in worst case we traverse the whole queue to insert an element in correct position
Space: O(n) because we store all elements in linked nodes
vs Alternative: Compared to a simple queue where insertion is O(1) but removal of highest priority is O(n), priority queue keeps removal O(1) but insertion O(n)
Edge Cases
Empty queue when removing
Returns None safely without error
DSA Python
if self.front is None:
            return None
Insert element with priority equal to existing nodes
Inserted after nodes with same priority to maintain stable order
DSA Python
while current.next and current.next.priority >= priority:
Insert into empty queue
New node becomes front
DSA Python
if self.front is None or priority > self.front.priority:
When to Use This Pattern
When you need to always process the most important item first, use a priority queue to keep elements sorted by priority automatically.
Common Mistakes
Mistake: Inserting new element at the end regardless of priority
Fix: Traverse and insert at correct position based on priority
Mistake: Removing from the end instead of front
Fix: Always remove from front to get highest priority element
Summary
A priority queue stores elements so that the highest priority is always at the front.
Use it when you want to process items by importance, not just arrival order.
The key is to insert elements in order so removal is always the highest priority.