
Problem
Solution
Submissions
Priority Queue Using a Heap
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
Implement a PriorityQueue class that supports the following operations: insert, get_highest_priority, extract_highest_priority, change_priority, and size.
Example 1
- Input:
pq = PriorityQueue()
pq.insert("Task A", 3)
pq.insert("Task B", 1)
pq.insert("Task C", 5)
highest = pq.get_highest_priority()
extracted = pq.extract_highest_priority() - Output: highest = "Task C" extracted = "Task C"
- Explanation:
- Step 1: Create a new PriorityQueue.
- Step 2: Insert "Task A" with priority 3.
- Step 3: Insert "Task B" with priority 1.
- Step 4: Insert "Task C" with priority 5.
- Step 5: Get the highest priority item without removing it, which is "Task C" (priority 5).
- Step 6: Extract the highest priority item, which is "Task C" (priority 5), and remove it from the queue.
Example 2
- Input:
pq = PriorityQueue()
pq.insert("Process 1", 10)
pq.insert("Process 2", 5)
pq.change_priority("Process 2", 15)
highest = pq.extract_highest_priority() - Output: highest = "Process 2"
- Explanation:
- Step 1: Create a new PriorityQueue.
- Step 2: Insert "Process 1" with priority 10.
- Step 3: Insert "Process 2" with priority 5.
- Step 4: Change the priority of "Process 2" from 5 to 15.
- Step 5: Extract the highest priority item, which is now "Process 2" (priority 15), and remove it from the queue.
Constraints
- 0 ≤ number of elements ≤ 10^5
- -10^9 ≤ priority ≤ 10^9
- Elements can be of any type, but must be hashable
- Time Complexity:
- insert: O(log n)
- get_highest_priority: O(1)
- extract_highest_priority: O(log n)
- change_priority: O(log n)
- size: O(1)
- Space Complexity: O(n) where n is the number of elements
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a binary max-heap to efficiently maintain the highest priority element
- Keep a separate map from values to their indices in the heap for efficient priority changes
- Implement the "heapify" operation to restore heap property after modifications
- Handle edge cases like empty heaps or non-existent elements
- Consider using the heapq module in Python, but modify it for a max-heap since heapq is a min-heap by default