Priority Queues With Distinct Elements
August 9, 2016
I recently needed a priority queue that contains no duplicate elements; if an attempt is made to add an element to the priority queue that is already present in the priority queue, the priority queue remains unchanged. As far as I know, none of the standard priority queue algorithms provide such a feature; they can’t, because they are all based on trees, and any element of the priority queue can be in either branch at any level of the tree.
Your task is to write a program that provides the data structure of priority queues with distinct elements. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here’s a solution in Java.
It extends Java’s built-in priority queue and overrides *add* and *remove*.
Here’s the output from the test in the main method.
Here is a Haskell version that uses the “priority search queue” provided by the psqueues package.
a bit late but….how about using a heap it acts as a priority queue and we can add an extra condition to check for duplicates and skipping over them
[…] a little bit of time. The second change is more important; we use the distinct priority queue of a previous exercise to eliminate duplicate candidates, which greatly reduced the amount of computation needed to find […]
A solution in Racket.