-1

I have the below code, I wanted to know what is the time complexity of this code when I am using PriorityQueue.

I have a listOfNumbers of size N

Queue<Integer> q = new PriorityQueue<>();
q.addAll(listOfNumbers);

while(q.size()>1) {
    q.add(q.poll()+q.poll()); // add sum of 2 least elements back to Queue
}

As per this post : Time Complexity of Java PriorityQueue (heap) insertion of n elements?

O(log n) time for the enqueing and dequeing methods (offer, poll, remove() and add)

Now how to calculate the time when I am adding the element back to Queue again.

learner
  • 4,858
  • 9
  • 47
  • 92

2 Answers2

2

The running time of your program is log(n) + log(n-1) + ... + log(1).

This is log(n!) (by repeated application of the log rule log(a) + log(b) = log(ab)).

log(n!) is Theta(n log n) see Is log(n!) = Θ(n·log(n))?

So your program runs in Theta(n log n) time.

Paul Hankin
  • 44,768
  • 11
  • 79
  • 97
1

On q.add(q.poll()+q.poll()); the number of element in queue is always O(N). So, the enqueue still works in O(log(N)).

Shridhar R Kulkarni
  • 4,794
  • 2
  • 27
  • 49