Sitemap

The Python Heap Cheat Sheet

Quick Tips and Essential LeetCode Patterns

In interviews, when a problem mentions keywords like “Top K,” “Frequent,” “Closest,” or “Median,” a Heap is what you should think about. In Python, this is implemented via the built-in heapq module.

What is a Heap?

A heap is a specialized binary tree that satisfies the Heap Property:

  • Min Heap: The parent node is smaller than or equal to its children. The root is the minimum.
  • Max Heap: The parent node is larger than or equal to its children. The root is the maximum.

Note: Python’s heapq implements a min heap by default.

Core Operations & Complexity

Heapify

Transforms a list into a heap in-place.

heapq.heapify(list)

Time complexity: O(n)

Push

Adds an element and maintains heap property.

heapq.heappush(h, item)

Time complexity: O(log n)

Pop

Removes and returns the smallest element.

smallest = heapq.heappop(h)

Get Allie Hsu’s stories in your inbox

Join Medium for free to get updates from this writer.

Time complexity: O(log n)

PushPop

Pushes a new item, then pops the smallest; more efficient than separate calls.

heapq.heappushpop(h, item)

Time complexity: O(log n)

Tips for Python Developers

Implementing a Max-Heap

Since Python only provides a Min-Heap, the standard workaround is to multiply your values by -1.

import heapq

nums = [1, 3, 5, 7, 9]
# Invert values to simulate Max-Heap
max_heap = [-x for x in nums]
heapq.heapify(max_heap)

# To get the actual maximum:
max_val = -heapq.heappop(max_heap) # Returns 9

Handling Objects or Coordinates

If you are storing coordinates, heapq compares the first element of the tuple. If there is a tie, it compares the second.

# (distance, x, y)
points = [(10, 1, 3), (5, 0, 1), (10, 2, 2)]
heapq.heapify(points)
# The heap will order them by distance first.

LeetCode Roadmap

Pattern 1: The “Top K” Elements

Pattern 2: Scheduling & Greedy Choices

Use a Heap when you need constant-time access O(1) to the minimum or maximum element while allowing O(log n) updates. It is the most balanced data structure for dynamic ordering.

A tech enthusiast who is keen to develop new skills