Priority Queues

Designing and analyzing priority queues.

  1. Priority queue interface
    1. PriorityNode
    2. Reference implementation
  2. Design and implement
    1. UnsortedArrayMinPQ
    2. HeapMinPQ
    3. OptimizedHeapMinPQ
    4. ReportAnalyzer
  3. Analyze and compare
    1. Asymptotic analysis
    2. Random testing

Priority queues are a fundamental building block for many real-world algorithms. For instance, if we only need to show the first 10 autocomplete matches in a specific order, a priority queue can be more efficient than sorting the entire list of all matches. Or, if we’re implementing a map navigation algorithm, a priority queue allows dynamic updates to the next-shortest path as the algorithm discovers new roads. Or, if we’re designing a worldwide web analytics dashboard, a priority queue can track statistics like the accessibility of the most commonly-visited web pages.

In this project, we will compare 4 implementations of priority queues to build a web analytics dashboard for tracking the occurrence of Web Content Accessibility Guideline recommendations. By the end of this project, students will be able to:

  • Design and implement multiple data structures to solve complex problems.
  • Analyze and compare implementation runtime and behavior by writing tests.

In the next project, we’ll also use your priority queues as a building block for shortest paths.

Priority queue interface

The MinPQ interface represents a priority queue that affords access to minimum-priority elements. Priority values are extrinsic to each element: rather than relying on a compareTo method, priority values are specified as arguments to the add and changePriority methods.

void add(E element, double priority)
Adds an element with the given priority value if the element is not already in this priority queue.
boolean contains(E element)
Returns true if the given element is in this priority queue.
E peekMin()
Returns the element with the minimum priority value.
E removeMin()
Returns and removes an element with the minimum priority value.
double getPriority(E element)
Returns the priority value for the given element if it is present.
void changePriority(E element, double priority)
Updates the given element’s associated priority value.
int size()
Returns the number of elements in this priority queue.

peekMin and removeMin should throw a NoSuchElementException if the priority queue is empty. getPriority and changePriority should throw a NoSuchElementException if the element is not present.

The interface also defines two default methods that rely on implementations of the above methods.

void addOrChangePriority(E element, double priority)
Adds an element with the given priority value if it is not already present. Otherwise, updates the priority value of the existing element.
if (!contains(element)) {
    add(element, priority);
} else {
    changePriority(element, priority);
}
boolean isEmpty()
Returns true if this priority queue contains no elements. Returns whether size() == 0.

A MinPQ cannot contain duplicate elements. However, different elements can have the same priority value. peekMin and removeMin may return any element with the minimum priority value.

Here’s a small example showing how to use the MinPQ interface with the DoubleMapMinPQ class included in the project. Try it out for yourself by creating a new class in IntelliJ with the following code in the main method.

MinPQ<String> pq = new DoubleMapMinPQ<>();
pq.add("1", 1.0);
pq.add("2", 2.0);
pq.add("3", 3.0);
pq.add("4", 4.0);
pq.add("5", 5.0);
pq.add("6", 6.0);

// Call methods to evaluate behavior.
pq.changePriority("3", 0.0);
pq.changePriority("1", 7.0);
while (!pq.isEmpty()) {
    System.out.println(pq.removeMin());
}
Why not just implement Java's PriorityQueue interface?

The java.util standard library includes a binary heap PriorityQueue class. Here are three reasons why we can’t implement Java’s PriorityQueue class in this project.

PriorityQueue is a class
We can’t implement the PriorityQueue class because it’s a class, not an interface. Although the Java developers designed Set, Map, and List as interfaces, priority queues are so commonly associated with binary heaps that the Java developers broke the pattern and defined PriorityQueue as a class.
PriorityQueue relies on compareTo
By default, PriorityQueue uses elements’ compareTo method to define the priority of an element. For example, the priority of the string “A” is less than “B” because “A” precedes “B” in the alphabet. This makes PriorityQueue great for sorting objects, but not great for applications like shortest paths.
PriorityQueue disaffords changing priority value
The fact that PriorityQueue uses elements’ compareTo methods reveals a hidden disaffordance. To change the priority of an object in PriorityQueue, we need to remove the element from the priority queue and then re-insert it. This workaround is not only inconvenient, but also inefficient and prone to bugs.

PriorityNode

Java collections typically only specify a single data type as in ArrayList<String>. But a MinPQ needs to keep track of each element as well as its associated priority value. We could do this by creating two lists: an ArrayList<T> for elements and an ArrayList<Double> for each element’s priority value. However, this approach requires us to ensure the state of both lists are always the same, which introduces additional complexity that makes the code harder to maintain and more brittle or susceptible to future bugs.

The PriorityNode class includes two fields representing an element together with its priority value so that it can be used in a Java collection.

List<PriorityNode<String>> elements = new ArrayList<>();
elements.add(new PriorityNode<>("example", 0));

Two PriorityNode objects are considered equal if and only if their elements are equal. Priority values are not checked for equality.

How will this property of PriorityNode equality help you implement MinPQ?

MinPQ does not allow duplicate elements, but does allow duplicate priority values. When using Java collections such as a List, methods like List.contains or List.remove will call the objects’ equals method to check for equality. The following contains call will return true, and the remove call will successfully remove the priority node even though their priority values are different.

elements.contains(new PriorityNode<>("example", 1));
elements.remove(new PriorityNode<>("example", 2));

Reference implementation

The project code includes a working DoubleMapMinPQ. This implementation is called “double map” because it combines the runtime benefits of two maps to solve the problem efficiently. The two maps work together to help achieve sublinear (logarithmic or better) runtime for every operation.

NavigableMap<Double, Set<E>> priorityToElement
Associates each unique priority value to all the elements with that priority value. Returning a minimum-priority element involves finding the set of minimum-priority elements and picking any element from that set.
Map<E, Double> elementToPriority
Associates each element with its priority value in order to speed-up contains and changePriority.

The state of both maps is synchronized across all methods. Any change to one data structure also requires a change to the other data structure.

Design and implement

Design and implement 3 implementations of the MinPQ interface. Then, use your MinPQ implementations to complete the ReportAnalyzer client class. Note that changePriority is not tested: you will need to justify correctness as noted in the specific deliverables.

UnsortedArrayMinPQ

Elements are added to an ArrayList in any order. Most operations may need to scan over the entire list.

HeapMinPQ

A standard binary heap priority queue that delegates all method calls to java.util.PriorityQueue. In other words, each MinPQ operation is implemented by calling the underlying PriorityQueue. This class contains only one field assigned to an instance of PriorityQueue. Our solution only uses 1-3 additional lines of code for most methods.

Explain the part of the HeapMinPQ class that you’re most proud of programming. Then, explain your changePriority method with a focus on justifying how it produces the correct behavior.

OptimizedHeapMinPQ

A optimized binary heap priority queue supported by a HashMap that associates each element with its array index to speed-up contains and changePriority. In other words, our heap, represented through an array, holds priority nodes organized by priority value. The HashMap acts as an “address book” for the indices of each priority node, helping us locate nodes within the heap.

Use this MinPQ.java class as a reference.

  1. Identify methods in the reference class that are most similar to our interface.
  2. Adapt the code to implement our interface. Make sure all tests pass before optimizing the code.
  3. Optimize the code by adding a HashMap synchronized to the state of the elements in the array.

Explain the part of the OptimizedHeapMinPQ class that you’re most proud of programming. Then, explain your changePriority method with a focus on justifying how it produces the correct behavior.

Run all the tests for UnsortedArrayMinPQ, HeapMinPQ, and OptimizedHeapMinPQ in IntelliJ and include a screenshot in your writeup showing a summary of the results. If the implementations pass all the test cases, explain an interesting bug that you addressed during your programming process. If the implementations do not pass all the test cases, explain what you think could be causing the problem.

ReportAnalyzer

In src/main/java/ReportAnalyzer.java, complete the main method to display the top 3 most commonly-reported Web Content Accessibility Guideline (WCAG) tags by using any MinPQ implementation to count the unique wcagTags. When displaying the most commonly-reported tags, use the wcagDefinitions to convert the tag identifiers to their descriptions.

Which WCAG descriptions were the top 3 most commonly-reported for the given data/reports?

Analyze and compare

Asymptotic analysis

Give a big-theta bound for the worst-case runtime of the removeMin and changePriority methods for each implementation, including DoubleMapMinPQ, with respect to N, the size of the priority queue. Explain the worst case and the runtime of each implementation in a couple sentences while referencing the code.

For all array-backed data structures, ignore the time it would take to resize the array.

java.util.PriorityQueue is implemented using an array-representation binary heap that

provides O(log(n)) time for the enqueuing and dequeuing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size).

Java’s HashSet and HashMap are implemented using resizing separate-chaining hash tables where the number of buckets is always similar to the size. Assume that the hash function evenly distributes elements across the buckets in the underlying array. The Java implementations include a further optimization.

Tree bucket optimization
When the size of a bucket exceeds 8 elements, the separate chain is automatically converted from a linked list to a red-black tree.

Explain the impact of tree bucket optimization assuming an even distribution of elements across the underlying array. Does the tree bucket optimization help, hurt, or not affect the asymptotic analysis given our assumptions?

Random testing

Write a random test in MinPQTests that simulates a large-scale version of the ReportAnalyzer. Read the data/wcag.tsv file and use randomness to sample WCAG tags until about 10000 tags have been counted by the reference and testing implementations. Then, remove all the tags from both implementations and check that the remove orders are consistent. Use the provided randomIntegersRandomPriorities method and the ReportAnalyzer that you implemented earlier to aid in writing your random test with WCAG tags. Your random test will likely be simpler than the sample randomIntegersRandomPriorities method.

Explain how your tests account for the possibility of ties in the remove order since multiple tags can share the same count.

After you have a functioning random test, modify it to better simulate our data/reports sample by upweighting the occurrence of the top 3 most commonly-reported tags. The top 3 tags may be hard-coded into your test, but be sure that your approach is sufficiently general: it should be easy to change the code to upweight the top 5 or top 10 most commonly-reported tags by changing the values in a data structure without making extensive changes to the rest of the test.

Explain how you upweighted the occurrence of the top 3 most commonly-reported tags.