What is the complexity (big-oh) for the remove()
function on the Priority Queue class in Java? I can't find anything documented anywhere, I think it's O(n), considering you have to find the element before you remove it and then reshuffle the tree. but I've seen others that disagree and think it's O(logn). Any ideas?
In java, there are two remove functions. remove() -> This is to remove the head/root, it takes O(logN) time. remove(Object o) -> This is to remove an arbitrary object. Finding this object takes O(N) time, and removing it takes O(logN) time.
To always get the largest element, we use priority queues. The time complexity would be: Creation of priority queue takes O(n) time.
The remove() method of PriorityQueue class removes a single instance of the specified element from this queue, only if it is present.
Geek, have you ever wondered what will happen if calls of remove() method exceed the elements present in the queue. In this scenario, it will continue to remove the elements that were there, and thereafter it will not find any element to remove priority-wise, so it will throw an exception which is as follows.
The confusion is actually caused by your "remove" function. In java, there are two remove functions.
remove() -> This is to remove the head/root, it takes O(logN) time.
remove(Object o) -> This is to remove an arbitrary object. Finding this object takes O(N) time, and removing it takes O(logN) time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With