Priority Queue - Problem
Implement a priority queue data structure using a heap. Your priority queue should support custom priority comparators and handle both min-heap and max-heap operations efficiently.
A priority queue is an abstract data type where each element has an associated priority. Elements with higher priority are served before elements with lower priority. When two elements have the same priority, they are served according to their order in the queue.
You need to implement the following operations:
insert(value, priority)- Add an element with given priorityextractMax()- Remove and return the element with highest prioritypeek()- Return the element with highest priority without removing itsize()- Return the number of elements in the queueisEmpty()- Check if the queue is empty
The implementation should use a binary heap for efficient operations and support custom comparator functions to determine priority ordering.
Input & Output
Example 1 — Basic Priority Queue Operations
$
Input:
operations = [["insert", 10, 3], ["insert", 5, 5], ["extractMax"], ["peek"], ["insert", 15, 2], ["extractMax"]]
›
Output:
[5, 10, 15]
💡 Note:
Insert 10 with priority 3, insert 5 with priority 5. ExtractMax returns 5 (highest priority). Peek shows 10. Insert 15 with priority 2. ExtractMax returns 10.
Example 2 — Same Priority Values
$
Input:
operations = [["insert", 20, 4], ["insert", 30, 4], ["extractMax"], ["extractMax"]]
›
Output:
[20, 30]
💡 Note:
Both elements have priority 4. The order depends on implementation - typically first inserted is returned first when priorities are equal.
Example 3 — Size and Empty Check
$
Input:
operations = [["isEmpty"], ["insert", 100, 1], ["size"], ["extractMax"], ["isEmpty"]]
›
Output:
[true, 1, 100, true]
💡 Note:
Initially empty (true), insert 100, size becomes 1, extract returns 100, queue becomes empty again (true).
Constraints
- 1 ≤ operations.length ≤ 1000
- -109 ≤ value ≤ 109
- 1 ≤ priority ≤ 109
- ExtractMax and Peek called only on non-empty queue
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code