1. Analyze the Request: The user wants a "priority queue implementation." This is a standard computer science data structure.
2. Determine the Goal: Provide a clear, understandable, and functional implementation of a Priority Queue.
3. Select the Language: Python is generally the most accessible for data structure demonstrations, but C++ or Java are also common. I'll stick to Python as the default unless specified otherwise, but perhaps offer a high-level explanation first.
4. Identify the Core Concept: A Priority Queue serves elements based on priority, not just FIFO (First-In-First-Out).
* High priority elements are served before low priority elements.
* Usually implemented using a Heap (Min-Heap or Max-Heap).
5. Determine the Scope/Approach:
* Approach A: Use the built-in library. (Most practical for real work). Python has heapq.
* Approach B: Implement from scratch. (Best for learning/educational purposes).
* Decision: I should provide both. Start with a from-scratch implementation to show how it works, then mention the built-in library for production use.
6. Drafting the From-Scratch Implementation (Python):
* Structure: A class PriorityQueue.
* Internal Storage: A list (array) representing a binary heap.
* Operations:
* push(item, priority): Add to the end, then "bubble up" (heapify up).
* pop(): Remove root (min/max), move last element to root, then "bubble down" (heapify down).
* peek(): Return root without removing.
* Min-Heap vs. Max-Heap: Min-Heap is standard (lowest number = highest priority). I'll stick to Min-Heap for simplicity.
7. Refining the Code (Mental Check):
* Need helper methods: _parent_index, _left_child_index, _right_child_index.
* Need _bubble_up (compare with parent, swap if smaller).
* Need _bubble_down (compare with children, swap with smaller child).
* Handling Tuples: Store (priority, value) in the list. Python compares tuples element-by-element.
8. Drafting the Built-in Implementation:
* Show how to use heapq.
* Note: heapq is a min-heap.
9. Structuring the Response:
* Introduction: Brief definition.
* Implementation (From Scratch): The code with comments explaining the heap logic.
* Explanation: How push and pop work (O(log n)).
* Built-in Library: The "pro" way using heapq.
10. Final Polish: Ensure the code is runnable and handles edge cases (like popping from an empty queue).
(Self-Correction during drafting): Should I make it generic? Yes, using Python's dynamic typing makes it easy. I'll ensure the priority is numeric.
Here is a robust implementation of a Priority Queue in Python.
While Python has a built-in module called heapq, implementing one from scratch using a Binary Min-Heap is the best way to understand how they work under the hood.
1. The Implementation (From Scratch)
This implementation uses a list to represent a binary tree structure. In this "Min-Heap" version, the smallest number has the highest priority and sits at the front of the queue.
python
class PriorityQueue:
def __init__(self):
# We initialize the heap with a dummy value at index 0.
# This makes the math for finding parent/child indices simpler.
self.heap = [0]
self.size = 0
def _bubble_up(self, index):
"""Move element up to maintain heap order."""
# While not at root, and current item < parent item
while index // 2 > 0:
if self.heap[index] < self.heap[index // 2]:
# Swap with parent
tmp = self.heap[index // 2]
self.heap[index // 2] = self.heap[index]
self.heap[index] = tmp
index = index // 2
def push(self, value):
"""Insert a value into the priority queue."""
self.heap.append(value)
self.size += 1
self._bubble_up(self.size)
def _bubble_down(self, index):
"""Move element down to maintain heap order."""
while (index * 2) <= self.size:
# Get the index of the smaller child
min_child_index = self._min_child(index)
# If current node is bigger than smallest child, swap
if self.heap[index] > self.heap[min_child_index]:
tmp = self.heap[index]
self.heap[index] = self.heap[min_child_index]
self.heap[min_child_index] = tmp
index = min_child_index
def _min_child(self, index):
left = index * 2
right = index * 2 + 1
# If right child doesn't exist, return left
if right > self.size:
return left
# Return the index of the child with the smaller value
if self.heap[left] < self.heap[right]:
return left
else:
return right
def pop(self):
"""Remove and return the highest priority item (smallest value)."""
if self.size == 0:
return None
root_val = self.heap[1] # The min value is always at index 1
# Move the last item to the root and reduce size
self.heap[1] = self.heap[self.size]
self.size -= 1
self.heap.pop()
# Move the new root down to its correct position
self._bubble_down(1)
return root_val
def peek(self):
"""Look at the highest priority item without removing it."""
if self.size == 0:
return None
return self.heap[1]
def is_empty(self):
return self.size == 0
2. How to Use It
Here is an example of pushing numbers in random order and popping them out in sorted (priority) order.
python
pq = PriorityQueue()
print("Pushing values: 5, 10, 3, 8, 1")
pq.push(5)
pq.push(10)
pq.push(3)
pq.push(8)
pq.push(1)
print(f"Peek top priority: {pq.peek()}") # Should be 1
print("\nPopping all items:")
while not pq.is_empty():
print(pq.pop(), end=" ")
# Output will be: 1 3 5 8 10
3. Complexity Analysis
Insertion (push): O(logn) — Because we potentially have to move the item up the height of the tree.
Deletion (pop): O(logn) — Because we replace the root and potentially have to move the new root all the way down to the bottom leaf.
Peek: O(1) — We always know the highest priority item is at index 1.
4. The "Production" Way (Using Python Standard Library)
If you are writing production code, you should use Python's built-in heapq module. It is highly optimized and written in C.
python
import heapq
# Create a simple list
pq = []
# heapq implements a Min-Heap by default
heapq.heappush(pq, 10)
heapq.heappush(pq, 1)
heapq.heappush(pq, 5)
print(heapq.heappop(pq)) # Output: 1
print(heapq.heappop(pq)) # Output: 5