Binary Heap Insertion Complexity

Coding
Heaps
Easy
What is the worst-case time complexity of inserting an element into a binary heap?
Hint 1

Insertion places the new element at the next open leaf position, then restores the heap property.

Hint 2

Count how many levels the element may need to move up.

Show worked solution
  1. 1. Describe the insertion process

    The new element is placed at the bottom of the heap and repeatedly swapped with its parent (sift-up) while it violates the heap property.

  2. 2. Bound the number of swaps

    A binary heap with elements has height , so the sift-up performs at most swaps.

Answer: O(log n)

Related roles: Browse quant jobs

Related problems