I would like to know what the time complexity of Java PriorityQueue.Add()
is for n
elements.
I understand that potential worse case insertion a single element is O(log(n))
, but it is not clear to me what the time complexity is for inserting a collection of n
elements?
I've seen claims from various sources (with no proofs) that the time to build a priority queue heap of n
elements it is O(n)
, and have also seen claims that it is O(nlog(n))
, which makes sense given insertion is O(log(n))
, which multiplied n
times would indeed equal O(nlog(n))
Note: I'm only interested in worse case, not amortized.
This question assumes there is a logical way to describe the act of populating a data structure (heap) with n
elements, that is different than simply considering n
x log(n)
insertions individually.
I'm making no assumptions regarding the input (such as a bounds on the set of input values, or a partially ordered input).
Answer: Time complexity for the methods offer & poll is O(log(n)) and for the peek() it is Constant time O(1) of java priority queue. SIDE NOTE: In Java programming, Java Priority Queue is implemented using Heap Data Structures, and Heap has O(log(n)) time complexity to insert and delete element.
Complexity: Time: O(log n), in the worst case, you will have to bubble up the inserted element up to the root of the tree. These will involve log n swaps, where n is the total number of nodes. Space: O(n)
Answer: Yes. Priority Queue allows duplicate values.
Yes, in C++ priority_queue, we may have duplicate values.
It seems like the insertion of n elements should be O(n log n)
Java PriorityQueue (Java Doc)
O(log n) time for the enqueing and dequeing methods (offer, poll, remove() and add)
O(n) for the remove(Object) and contains(Object) methods
O(1) for the retrieval methods (peek, element, and size)
These time complexities seem all worst case (wiki), except for .add()
. You are right to question the bounds as the Java Doc also states to the extension of this unbound structure:
The details of the growth policy are not specified
As they state in the Doc as well, the PriorityQueue is based on an array with a specific initial capacity. I would assume that the growth will cost O(n) time, which then would also be the worst case time complexity for .add()
.
To get a guaranteed O(n log n) time for adding n elements you may state the size of your n elements to omit extension of the container:
PriorityQueue(int initialCapacity)
EDIT: To the claim of O(n) time for construction is correct (as stated by @pjs in the comments). This procedure is often called heapify and works on an pre existing array that is used to construct a binary tree on it in O(n) 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