AniUI Academy

A priority queue with your own comparator

hardData Structures+350 XPPractice

A request scheduler sends the user-visible fetch before the prefetch; a notification centre shows the critical alert above the chatty one. Both need a queue ordered by priority rather than arrival, with the rule supplied by the caller.

Implement a PriorityQueue class. new PriorityQueue(compare) takes an optional comparator with the same contract as Array#sort: compare(a, b) returns a negative number when a should come out before b, a positive number when it should come out after, and zero when they are equally urgent. When no comparator is given, default to ascending numeric order, (a, b) => a - b. push(item) inserts an item and returns the new size. pop() removes and returns the item that comes first under the comparator, or undefined when the queue is empty. peek() returns that item without removing it, or undefined when empty. size() returns how many items are held, and isEmpty() returns true when it holds none.

The order among items the comparator calls equal is not defined, so do not rely on it.

Examples

const q = new PriorityQueue();
[5, 1, 4, 3].forEach((n) => q.push(n));
q.pop(); // 1
q.pop(); // 3
q.pop(); // 4
q.pop(); // 5

The default comparator is ascending numeric order.

const q = new PriorityQueue((a, b) => a.priority - b.priority);
q.push({ name: "prefetch", priority: 9 });
q.push({ name: "render", priority: 1 });
q.push({ name: "analytics", priority: 5 });
q.pop().name; // "render"

A custom comparator can order by any field of an object.

What it has to do

  • With no comparator, pop() returns numbers in ascending order.
  • A supplied comparator decides the order, including over objects.
  • pop() and peek() return undefined on an empty queue.
  • push returns the new size and pushes may be interleaved with pops.
  • Do not sort the whole collection on every push.

Notes

  • A binary-heap implementation gets push and pop to O(log n); peek is O(1).
  • Sorting the array on every push would be O(n log n) per push — fine for a dozen items, catastrophic for a scheduler.
  • A negative comparator result means a comes out before b, matching Array#sort. Passing (a, b) => b - a reverses the order into a max-queue.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.