📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    What is the typical time complexity for inserting an

    element into a java.util.PriorityQueue with N elements?     import java.util.PriorityQueue;     public class HeapQuestion3 {         public static void main(String[] args) {             PriorityQueue pq = new PriorityQueue();             // Assume pq already contains N elements             pq.add(100); // What is the time complexity of this operation?         }     }
    A O(1) Correct Answer Incorrect Answer
    B O(log N) Correct Answer Incorrect Answer
    C O(N) Correct Answer Incorrect Answer
    D O(N log N) Correct Answer Incorrect Answer
    E O(N^2) Correct Answer Incorrect Answer

    Solution

    A PriorityQueue in Java is implemented using a binary heap. When an element is added (add() or offer()), it is initially placed at the end of the underlying array (which represents the heap). To maintain the heap property, this new element then "bubbles up" (or "heapifies up") by repeatedly swapping with its parent until its correct position is found. In a binary heap, the height of the tree is logarithmic with respect to the number of elements (log N). Therefore, the maximum number of swaps (and comparisons) required to place an element is proportional to the height of the heap, resulting in an O(log N) time complexity for insertion.

    Practice Next
    ask-question