I am doing a practice problem Practice IT Kth Smallest
This problem is basically you're passed in a PriorityQueue and a certain k, and you are to return the kth smallest value in that PriorityQueue. You are also to restore the PriorityQueue to its initial state and can use one stack or queue as an auxiliary data structure.
My higher level pseudo thinking is that because the PriorityQueue acts as a min heap already, from Java PriorityQueue, all I really have to do (my algorithm) is:
Remove k elements from the PriorityQueue
Store the kth smallest value as a local variable
Push removed k elements onto a Stack (Stack so I can add elements in the same order)
Pop all the elements from the Stack and re add them back into the PriorityQueue
Return the kth smallest value
Here is the code to do all of that:
public int kthSmallest(PriorityQueue<Integer> pQ, int k) {
if(k <= 0 || k > pQ.size()) {
throw new IllegalArgumentException();
} else {
Stack<Integer> aux = new Stack<Integer>();
int kThSmallest = -1;
for(int c=0;c<k;c++){
int element = pQ.remove();
if(c == k-1)
kThSmallest = element;
aux.push(element);
}
while(!aux.isEmpty())
pQ.add(aux.pop());
return kThSmallest;
}
}
When I run the program I get all the right outputs, in terms of kth smallest, but I can't restore the state of my PriorityQueue. For example, when passing in a PriorityQueue of:
[-3, 9, 17, 22, 42, 81] with a k of 3
... my algorithm produces the right result, 17, but it changes the state of the PriorityQueue to [-3, 17, 9, 81, 22, 42]
, which is unexpected.
I thought about making a copy of the PriorityQueue but that violates one the conditions, "you can use one stack or queue as an auxiliary data structure".
How can I go about restoring the state of the PriorityQueue?
PriorityQueue
? – kraskevich