What is the time complexity of inserting an element into a binary heap?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer:
c) O(log n)
Explanation:
The time complexity of inserting an element into a binary heap is O(log n). This is because after inserting the element at the end, the heap property may need to be restored, which requires traversing up the heap to re-establish the correct order.
This process, called “heapify,” ensures that the newly inserted element is correctly placed according to the heap’s properties. Since the height of a binary heap is log n, the heapify process takes O(log n) time.
This efficiency makes heaps ideal for priority queues, where both insertions and deletions are done frequently.
Reference:
DSA (Data Structures and Algorithms) MCQ Questions and Answers