Heap Implementation & Library Resource - aloalgo

Heap Implementation & Library

In interviews, you'll typically use built-in heap libraries. Here's how heaps work internally and how to use them in different languages.

Core Operations

  • Push (Insert): Add element, bubble up to maintain heap property - O(log n)
  • Pop (Extract): Remove root, replace with last element, bubble down - O(log n)
  • Peek: Return the root element without removing - O(1)
  • Heapify: Convert an array into a heap - O(n)

Python: heapq Module

Python's heapq implements a min-heap by default.

Max-Heap in Python

Python only has min-heap. For max-heap, negate the values.

Java: PriorityQueue

Java's PriorityQueue is a min-heap by default. Use a comparator for max-heap.

JavaScript: Manual Implementation

JavaScript doesn't have a built-in heap. You can use a simple array with sort, or implement a heap class.

Heap with Custom Objects

Often you need to heap objects by a specific property.

Complexity Summary

  • Push: O(log n)
  • Pop: O(log n)
  • Peek: O(1)
  • Heapify: O(n)
  • Space: O(n)
Was this helpful?
© 2026 aloalgo. All rights reserved.