Priority Queue
A priority queue is a special type of queue in which elements are inserted with a priority and the element with the highest priority is removed first. Your implementation should allow enqueuing elements with a priority and dequeuing them based on that priority (lower number = higher priority by default). If two elements have the same priority, they should be dequeued in the order they were added.
Your priority queue should support the following operations:
enqueue(value, priority)– adds an element with a given priority.dequeue()– removes and returns the element with the highest priority (lowest priority number).peek()– returns the element with the highest priority without removing it.isEmpty()– returns true if the queue is empty.size()– returns the number of elements in the queue.
Example Inputs & Outputs
const pq = new PriorityQueue(); pq.enqueue('Clean the house', 2); pq.enqueue('Do the dishes', 1); pq.enqueue('Take out the trash', 2); pq.dequeue(); // → 'Do the dishes' pq.peek(); // → 'Clean the house' pq.size(); // → 2 pq.isEmpty(); // → false
Constraints & Edge Cases
- Lower numerical priority means higher importance (priority 1 > priority 3).
- Stable ordering: elements with same priority should follow FIFO order.
- Support all listed methods: enqueue, dequeue, peek, isEmpty, size.
- The queue can hold any data type as
value. dequeue()andpeek()should returnnullif the queue is empty.
Companies:
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
