Time and Space complexities for common operations in Heap

Time Complexity

Operation
Time Complexity
Explanation

Insert

O(log n)

Inserts an element into the heap. The time complexity is O(log n) because the element must be inserted into the correct position in the heap, which requires a binary search.

Delete

O(log n)

Deletes the element at the root of the heap. The time complexity is O(log n) because the element must be removed from the heap and the heap property must be restored, which requires a binary search and a heapify operation.

Peek

O(1)

Returns the element at the root of the heap without removing it. The time complexity is O(1) because the element is stored at the root of the heap.

Remove Min/Max

O(log n)

Removes the minimum or maximum element from the heap. The time complexity is O(log n) because the element must be removed from the heap and the heap property must be restored, which requires a binary search and a heapify operation.

Build Heap

O(n)

Creates a heap from an array. The time complexity is O(n) because the elements of the array must be sorted in order to create a heap.

Heapify

O(log n)

Restores the heap property to a subtree of the heap. The time complexity is O(log n) because the subtree must be sorted in order to restore the heap property.

Sort

O(n log n)

Sorts an array using a heap. The time complexity is O(n log n) because the heap is used to repeatedly remove the minimum element from the array, which takes O(log n) time each.

Space Complexity

Operation
Space Complexity
Explanation

Insert

O(log n)

The new element is added to the bottom of the heap, and then the heap is rebuilt in O(log n) time.

Delete Min/Max

O(log n)

The minimum or maximum element is removed from the heap, and then the heap is rebuilt in O(log n) time.

Decrease Key

O(log n)

The key of an element is decreased, and then the heap is rebuilt in O(log n) time.

Increase Key

O(log n)

The key of an element is increased, and then the heap is rebuilt in O(log n) time.

Last updated

Was this helpful?