3

Given the code below:

pq.offer(x);
pq.poll();

For the first line code, element x is inserted into Priority Queue pq, the time complexity of the offer is log(k), where k is the size of pq.

Then my question is, for the second line code that immediately follows the first line, what'll be the time complexity for poll() ?

After first line offer, the pq has already been sorted, so poll will simply retrieve and remove the head of queue, then I think it should be O(1), correct?

Thanks

3
  • Items in a Java PriorityQueue are not sorted. Items are inserted into a binary heap, which is an ordered, but not necessarily stored, data structure. Commented Oct 3, 2017 at 3:05
  • @JimMischel - they are stored all right. Just not sorted. Commented Oct 3, 2017 at 11:00
  • @HenkHolterman: Thanks. Looks like last night I was CEO of typos-r-us. Commented Oct 3, 2017 at 13:09

2 Answers 2

4

According to the source code of PriorityQueue#poll, it seems that the operation is O(log n):

@SuppressWarnings("unchecked")
public E poll() {
    if (size == 0)
        return null;
    int s = --size;
    modCount++;
    E result = (E) queue[0];
    E x = (E) queue[s];
    queue[s] = null;
    if (s != 0)
        siftDown(0, x);
    return result;
}

This is because siftDown is O(log n), due to the data within the PriorityQueue being stored as a heap.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! Yeah I just read the source code and u r correct.
4

Adding to and removing from a heap-based PQ are both O(log(N)).

This is stated clearly in the Javadoc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.