Facebook Pixel

Priority Queue

JavaScript
medium
25 mins

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() and peek() should return null if the queue is empty.

Companies:

amazon
paypal
swiggy

Solve Similar questions 🔥