1. Understand the Goal: The user wants an implementation of a min-heap and a max-heap. The request is broad, so I should provide a clear, standard implementation (usually in Python or Java, but Python is generally more accessible for algorithms) and explain the core concepts.
-
Choose the Language: Python is excellent for this because:
- It has a built-in
heapq module (min-heap), which serves as a great reference for what "good" looks like.
- The syntax is clean, making the logic (swapping, bubbling up/down) easy to read.
- I can implement a class-based structure to encapsulate the logic.
-
Core Heap Operations: Regardless of Min or Max, the logic is almost identical, just the comparison operators change.
insert (push): Add to end, bubble up (heapify up).
extract (pop): Remove root, move last element to root, bubble down (heapify down).
peek: Look at the root.
- Helper methods:
parent, left_child, right_child, swap.
-
Designing the Class Structure:
- Option A: Two separate classes. Redundant code.
- Option B: A base class
Heap with abstract comparison methods, then MinHeap and MaxHeap inherit. A bit over-engineered for a simple request.
- Option C: A single class that takes a comparator (like Python's
heapq doesn't do natively, but a custom class could).
- Decision: To make it educational and copy-pasteable, I will write a
MinHeap class first, fully documented. Then, I will show how to convert it to a MaxHeap (or create a generic one).
- Better Decision: Let's create a single
Heap class that handles both via a is_min_heap flag or a comparator function. This reduces code duplication and shows better software design.
Wait, let's keep it simple first. If someone asks for "min-heap and max-heap implementation," they usually want to see the specific logic for bubble_up where current < parent vs current > parent.
Let's provide:
- A custom
MinHeap class implementation (educational).
- A note on how
MaxHeap is just inverting the comparison (or using negative numbers in a min-heap).
- Python's built-in
heapq usage (practical).
-
Drafting the Code (Mental or Scratchpad):
-
Storage: Array/List.
-
Indices:
- Parent:
(i - 1) // 2
- Left:
2 * i + 1
- Right:
2 * i + 2
-
MinHeap Insert:
def push(self, val):
self.heap.append(val)
self._bubble_up(len(self.heap) - 1)
def _bubble_up(self, index):
while index > 0:
parent = (index - 1) // 2
if self.heap[index] < self.heap[parent]: # Comparison
swap(index, parent)
index = parent
else: break
-
MinHeap Pop:
def pop(self):
if empty: return None
if size 1: return pop()
root = self.heap[0]
self.heap[0] = self.heap.pop() # Move last to root
self._bubble_down(0)
return root
def _bubble_down(self, index):
while True:
left = 2*i + 1
right = 2*i + 2
smallest = index
if left < size and heap[left] < heap[smallest]: smallest = left
if right < size and heap[right] < heap[smallest]: smallest = right
if smallest != index:
swap(index, smallest)
index = smallest
else: break
-
Refining the Approach:
Writing two almost identical classes is verbose. I will write a Generic Heap class that accepts a comparator. This is elegant, extensible, and answers the prompt efficiently.
- Class
Heap
- Init takes
comparator (lambda a, b: bool).
- MinHeap =
Heap(lambda a, b: a < b)
- MaxHeap =
Heap(lambda a, b: a > b)
-
Structure of the Output:
- Concept: Briefly explain the array representation and indices.
- Implementation (Python): Provide a clean, unified class.
- Usage: Show how to create Min and Max versions using that class.
- Alternative (Python Built-in): Briefly mention
heapq because that's what you actually use in production.
-
Writing the Code (Self-Correction during drafting):
- Make sure to handle empty heaps in
pop.
- Make sure to handle heaps with only one element in
pop.
- The
comparator logic needs to be clear.
-
Final Code Polish:
Let's stick to a readable Python implementation. I will implement a single Heap class to avoid code repetition, as Min and Max heaps are identical except for the comparison logic during the "heapify" steps.
- Method
_bubble_up: Compare current with parent.
- Method
_bubble_down: Compare current with children.
Wait, for _bubble_down in a generic heap:
I need to find the "target" child to swap with.
MinHeap: Swap with the smaller child.
MaxHeap: Swap with the larger child.
The generic comparator compare(child, current) implies "should child be above current?".
Actually, it's easier to find the child that should be the new parent.
Let's stick to a simpler approach: Implement MinHeap explicitly, and provide a MaxHeap wrapper or class.
Revised Plan:
- Define
MinHeap class (classic implementation).
- Define
MaxHeap class (classic implementation, or inherit).
- Actually, let's do a Template Pattern or just separate classes for clarity, as it's often easier for beginners to read separate logic than abstracted logic.
Let's do separate classes but structured nicely. Or, better yet, a single class with a flag.
Let's go with the Comparator approach. It is the most robust.
Code:
class Heap:
def __init__(self, comparator):
self.heap = []
self.comparator = comparator # True if a should be parent of b
_bubble_up: if self.comparator(self.heap[index], self.heap[parent]): swap
_bubble_down: Find highest_priority_child. if self.comparator(child, self.heap[index]): swap.
-
Adding Python's heapq:
It's crucial to mention that Python only implements a MinHeap natively. To do a MaxHeap, you insert negative values. I should demonstrate this "hack" as it's industry standard for Python.
-
Final Review of the Plan:
- Intro: What is it? (Binary tree in array).
- The Class: A unified
Heap class using a comparator.
- Min/Max Usage: Code snippets creating instances.
- Python Standard Lib:
import heapq example.
This looks solid. I will generate the response based on this structure.
Here is a clean, object-oriented implementation of a Heap in Python.
To make this efficient and avoid code duplication, I have created a single Heap class that takes a comparator function. This allows the exact same logic to function as both a Min-Heap and a Max-Heap depending on how you initialize it.
1. The Implementation
class Heap:
def __init__(self, comparator=lambda x, y: x < y):
"""
Initializes the heap.
:param comparator: A function that returns True if the first argument
should have higher priority (be higher in the tree).
Default is Min-Heap (x < y).
"""
self.heap = []
self.comparator = comparator
def _parent(self, index):
return (index - 1) // 2
def _left_child(self, index):
return 2 * index + 1
def _right_child(self, index):
return 2 * index + 2
def push(self, item):
"""Inserts an item into the heap."""
self.heap.append(item)
self._heapify_up(len(self.heap) - 1)
def pop(self):
"""Removes and returns the top item (min or max)."""
if not self.heap:
return None
if len(self.heap) == 1:
return self.heap.pop()
# Save the root item to return
root = self.heap[0]
# Move the last item to the root and remove the last item
self.heap[0] = self.heap.pop()
# Move the new root down to its correct position
self._heapify_down(0)
return root
def peek(self):
"""Returns the top item without removing it."""
if not self.heap:
return None
return self.heap[0]
def _swap(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
def _heapify_up(self, index):
"""Moves the item at index up until the heap property is restored."""
while index > 0:
parent_idx = self._parent(index)
# If current item has higher priority than parent, swap them
if self.comparator(self.heap[index], self.heap[parent_idx]):
self._swap(index, parent_idx)
index = parent_idx
else:
break
def _heapify_down(self, index):
"""Moves the item at index down until the heap property is restored."""
size = len(self.heap)
while True:
left = self._left_child(index)
right = self._right_child(index)
priority_index = index
# Compare with left child
if left < size and self.comparator(self.heap[left], self.heap[priority_index]):
priority_index = left
# Compare with right child
if right < size and self.comparator(self.heap[right], self.heap[priority_index]):
priority_index = right
# If the current node is already in the correct spot, stop
if priority_index == index:
break
self._swap(index, priority_index)
index = priority_index
def __len__(self):
return len(self.heap)
def __str__(self):
return str(self.heap)
2. Usage Examples
Here is how you use the class above to create both a Min-Heap and a Max-Heap.
Min-Heap
In a Min-Heap, the smallest number is at the root. The comparator checks if x < y.
# Default behavior is Min-Heap
min_heap = Heap()
min_heap.push(10)
min_heap.push(5)
min_heap.push(30)
min_heap.push(2)
print("Min-Heap array:", min_heap)
# Output will look roughly like: [2, 5, 30, 10] (structure varies)
print("Peek:", min_heap.peek()) # 2
print("Popping:", min_heap.pop()) # 2
print("Popping:", min_heap.pop()) # 5
Max-Heap
In a Max-Heap, the largest number is at the root. We simply pass a lambda that checks if x > y.
# Pass a custom comparator for Max-Heap
max_heap = Heap(comparator=lambda x, y: x > y)
max_heap.push(10)
max_heap.push(5)
max_heap.push(30)
max_heap.push(2)
print("Max-Heap array:", max_heap)
print("Peek:", max_heap.peek()) # 30
print("Popping:", max_heap.pop()) # 30
print("Popping:", max_heap.pop()) # 10
3. Time Complexity
One of the main reasons Heaps are used is their efficiency.
| Operation | Time Complexity | Description |
|---|
| Push (Insert) | O(logn) | The height of a binary tree is logn, so we swap up the tree at most that many times. |
| Pop (Extract) | O(logn) | We swap the root with the last element and bubble down ( steps). |
4. Python Built-in Alternative
If you are writing production code and not solving an algorithm interview question, Python has a built-in module called heapq.
Note: heapq only implements a Min-Heap.
import heapq
# Min-Heap
data = [10, 5, 30, 2]
heapq.heapify(data) # Turns list into heap in-place
print(data[0]) # Peek: 2
heapq.heappush(data, 1)
print(heapq.heappop(data)) # Pop: 1
To make a Max-Heap with heapq:
A common trick is to insert the negative values of your numbers.
- Insert
-x
- When you pop, multiply the result by
-1.