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?
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.
O(logN)
time? In my head, I was thinking something like re-construct the PriorityQueue for the remaining N-1 element, which takes O(NlogN)
time in Java, O(N)
in theory. Correct me if I am wrong.. –
Cranwell The complexity for remove is O(N) since the complexity for contains is O(N) (in java's priority queue class)
One way this can be made O(logN) in your own Priority Queue implementation is to maintain an auxiliary data structure like a HashMap that maintains the mappings from a value in the priority queue to its position in the queue. So, at any given time - you would know the index position of any value.
Note that this modification does not affect the running time of any of the existing operations - you would only need to update the mappings during the heapify operations.
According to Oracle documentation: "Implementation note: this implementation provides O(log(n)) time for the enqueing and dequeing 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)."
remove()
and poll()
are the same except for missing element semantics. Removing a specific item (remove(Object)
) is O(n)
. I think the question wasn't clear and this is a valid answer too... –
Someone Please check: http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
"this implementation provides O(log(n)) time for the enqueing and dequeing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods"
Thus for poll() and remove(), that' log(N) But for remove(object), that log(N)
© 2022 - 2024 — McMap. All rights reserved.