Implement Priority Queue - aloalgo

Implement Priority Queue

Hard

Implement a max-priority queue that supports push, pop, and peek operations.

Your PriorityQueue class should have the following methods:

  • push(val): Pushes the integer val onto the priority queue.
  • pop(): Removes and returns the element with the highest value.
  • peek(): Returns the element with the highest value without removing it.

You may assume that:

  • pop and peek are never called on an empty queue.
  • val is in the range [-10^6, 10^6].

Example 1

Input
p = PriorityQueue()
p.push(3)
p.push(5)
p.push(1)
p.pop()
p.peek()
p.pop()
Output
[5, 3, 3]
Explanation:

Push 3, 5, and 1. Pop returns 5 (the highest). Peek returns 3 (the new highest) without removing it. Pop returns 3.

Example 2

Input
p = PriorityQueue()
p.push(10)
p.push(20)
p.pop()
p.push(15)
p.pop()
p.pop()
Output
[20, 15, 10]
Explanation:

Push 10 and 20. Pop returns 20. Push 15. Pop returns 15. Pop returns 10.

Example 3

Input
p = PriorityQueue()
p.push(7)
p.peek()
p.peek()
p.pop()
Output
[7, 7, 7]
Explanation:

Push 7. Peek returns 7 twice without removing it. Pop returns 7.

Loading...
Input
p = PriorityQueue()
p.push(3)
p.push(5)
p.push(1)
p.pop()
p.peek()
p.pop()
Output
[5, 3, 3]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!