PQ Data Structure
Applications of PQs:
Time Complexility
Operation | T.C. |
---|---|
polling | O(log N) |
peeking | O(1) |
Adding | O(log N) |
Naive Removing | O(n) |
Advanced Removing with help from a Hash-table. |
O(log(n)) |
Naive Contains | O(n) |
Contains check with help of Hash-table. |
O(1) |
Priority Queue (PQ) DS Implementation:
Java PriorityQueue demo:
Problem: Change MinPQ into MaxPQ
Often the standard library of most programming languages only provide a Min-PQ which sorts the smallest elements first but sometimes we need a Max-PQ.
Hint:
Approach 1: Using custom Comparable
In MinPQ when data is inserted a comparision is done to decide the lowest between two to keep it on top which we can use a custom comparable to return the highest number in the comparision which will be kept on top.
Source code: Github link: MinPQToMaxPQUsingComparable.java
/**
* Create Max priority queue using provided data.
*
* @param data
* @return
*/
private static Queue<Integer> constructMaxPQueue(int[] data) {
/*
* Comparator returns a negative integer, zero, or a positive integer as the first argument
* is less than, equal to, or greater than the second.
*/
final Queue<Integer> maxPQ = new PriorityQueue<>(new Comparator<Integer>() {
/**
* {@inheritDoc}
*
* Reverse the return value to get Max Priority Queue.
*
* arg1 < arg2 ----> 1 [Default / MinPQ will return 1]
* arg1 < arg2 ----> 0 [Default / MinPQ will return 0]
* arg1 < arg2 ----> -1 [Default / MinPQ will return -1]
*
* @param arg1 the first object to be compared.
* @param arg2 the second object to be compared.
* @return
*/
@Override
public int compare(Integer arg1, Integer arg2) {
if (arg1 > arg2) {
return -1;
} else if (arg1.equals(arg2)) {
return 0;
} else {
return 1;
}
}
});
StringBuilder sb = new StringBuilder("Input array: [");
for (int t : data) {
maxPQ.offer(t);
sb.append(t).append(", ");
}
sb.append("]");
System.out.println(sb);
return maxPQ;
}
Approach 2: Negate the numbers
Source code: Github link: MinPQToMaxPQByNegatingValues.java
/**
* Create Max priority queue using provided data.
*
* @param data
* @return
*/
private static Queue<Integer> constructMaxPQueue(int[] data) {
final Queue<Integer> maxPQ = new PriorityQueue<>();
StringBuilder sb = new StringBuilder("Input array: [");
for (int t : data) {
/*
* Negate the value while adding to the queue.
* While polling back, negate them back before processing
*/
maxPQ.offer(t * -1);
sb.append(t).append(", ");
}
sb.append("]");
System.out.println(sb);
return maxPQ;
}
/**
* Print Queue data using `poll()` API.
*
* @param queue
*/
private static void print(Queue<Integer> queue) {
queue = new PriorityQueue<>(queue);
StringBuilder sb = new StringBuilder("MaxPQ : ").append(" {");
while (!queue.isEmpty()) {
/*
* Negating the value to transform it to the actual value.
*/
sb.append(queue.poll() * -1).append(", ");
}
sb.append("}");
System.out.println(sb.toString());
}
References: