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 priority
  • extractMax() - Remove and return the element with highest priority
  • peek() - Return the element with highest priority without removing it
  • size() - Return the number of elements in the queue
  • isEmpty() - 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
INPUTALGORITHMRESULTinsert(10, 3)insert(5, 5)extractMax()extractMax()1Build Max HeapMaintain parent ≥ children2Bubble Up/DownO(log n) rebalancing3Extract RootAlways highest priority5:510:3Extract Results:510Highest priorities firstOutput: [5, 10]Key Insight:A binary max-heap keeps the highest priority element at the root, enabling O(1) peekand O(log n) insert/extract operations through efficient bubble up/down rebalancing.TutorialsPoint - Priority Queue | Max Heap Implementation
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
67.0K Views
High Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen