The user wants a min-heap and max-heap implementation.
I need to decide on the programming language. Python is a good choice for readability and common usage in interviews/educational contexts. I'll stick with Python but structure it so it's easily understandable.
Core Concepts:
- Heap Property:
- Min-Heap: Parent ≤ Children. Smallest element at the root.
- Max-Heap: Parent ≥ Children. Largest element at the root.
- Binary Tree Structure: Heaps are usually implemented as complete binary trees. This allows for an array-based implementation.
- Array Indexing:
- If index i is the parent:
- Left Child: 2⋅i+1
- Right Child: 2⋅i+2
- If index i is a child:
- Parent: (i−1)//2
- Key Operations:
insert (push): Add to the end, then "bubble up" (heapify up) to restore property.
extract (pop): Remove root, move last element to root, then "bubble down" (heapify down) to restore property.
peek: Look at root.
size, is_empty.
Implementation Strategy:
- Base Class: Since Min-Heap and Max-Heap share almost all logic except the comparison operator (< vs >), I can create a base
Heap class or use a comparison lambda/function passed to the constructor.
- Option A: Two separate classes. Simple to read, slightly repetitive code.
- Option B: One class with a
comparator. Flexible, DRY (Don't Repeat Yourself), but slightly more complex to read initially.
- Option C: Inheritance.
- Decision: I will provide two separate classes for clarity because people often copy-paste specific ones. However, to be efficient, I'll structure the code so the logic is clear. Actually, a single class with a comparator is "cleaner" engineering, but for a prompt like "Create a min-heap and max-heap", showing the specific logic for each is often better for understanding the algorithm.
- Revised Decision: I will create a single
Heap class that takes a comparator. This demonstrates good software design principles. Then I'll show how to instantiate it as a MinHeap and MaxHeap. Wait, the prompt asks for implementations (plural). Explicit classes MinHeap and MaxHeap are usually expected in algorithmic contexts.
- Final Plan: I'll write a base class
Heap that handles array mechanics, and two subclasses MinHeap and MaxHeap that implement the specific _compare logic. This is the best balance of clarity and code reuse.
Drafting the Code (Mental or scratchpad):
-
_heapify_up(index):
- While index>0:
- Parent index = (index−1)//2
- If comparison(current, parent) implies swap:
- Else break
-
_heapify_down(index):
- While left child exists:
- Find "target" child (min child for min-heap, max child for max-heap).
- If comparison(current, target) implies swap:
- Swap
- index = target child
- Else break
Language: Python.
Refining the Comparison Logic:
- MinHeap: If
current < parent, swap.
- MaxHeap: If
current > parent, swap.
- MinHeap Bubble Down: Swap with smaller child. If
current > child, swap.
- MaxHeap Bubble Down: Swap with larger child. If
current < child, swap.
Let's simplify. I'll provide a generic class and then two concrete wrapper classes. It's the most educational approach.
Steps:
- Define the
Heap class.
- Methods:
push, pop, peek.
- Internal methods:
_swap, _parent, _left_child, _right_child.
- Logic:
_sift_up, _sift_down.
- Subclasses
MinHeap and MaxHeap defining the _Comparator.
Self-Correction during drafting:
Writing a generic comparator in Python might look like if self.comparator(a, b): swap.
For MinHeap, comparator is a < b.
For MaxHeap, comparator is a > b.
However, _sift_down logic is slightly different from _sift_up.
Actually, usually _sift_down finds the appropriate child.
In MinHeap: find smaller child. If parent > smaller child, swap.
In MaxHeap: find larger child. If parent < larger child, swap.
Okay, to make it standard and robust, I will implement a MinHeap fully, and then inherit or alias it for MaxHeap by negating values or passing a different comparator.
Actually, the cleanest way to teach this without over-engineering is to write a class that accepts a key or comparator.
Let's stick to the "Comparator" pattern. It is the most Pythonic and professional way to handle both.
Structure of the response:
- Conceptual explanation: Briefly explain the array mapping (2i+1, etc.).
- The Code: A robust, generic implementation using a comparator.
- Usage Examples: Show how to use it for both Min and Max.
Code Structure:
class Heap:
def __init__(self, comparator):
self.heap = []
self.comparator = comparator # Comparator returns True if order is correct
# ... push, pop, peek ...
# ... helpers ...
Wait, comparators are tricky.
Let's define _should_swap(child_idx, parent_idx).
For MinHeap: return heap[child] < heap[parent].
For MaxHeap: return heap[child] > heap[parent].
For _sift_down:
We need to pick which child to swap with.
For MinHeap: Pick smaller child. If parent > picked_child, swap.
For MaxHeap: Pick larger child. If parent < picked_child, swap.
To make the code easy to copy-paste, I will implement a MinHeap class first, fully commented. Then I will show how to modify specific lines for a MaxHeap. Or better, a unified class.
Decision: I will provide a unified Heap class that accepts a comparator function, along with pre-configured MinHeap and MaxHeap classes that inherit from it. This is the most useful answer.
Detailed Logic for the Unified Class:
push(val): append, _sift_up.
pop(): swap root with last, pop, _sift_down on root.
_sift_up(i): compare with parent. If better priority, swap.
_sift_down(i): find child with best priority. If child has better priority than self, swap.
I will use Python's heapq logic as a mental reference but implement the raw array manipulation manually to demonstrate the actual algorithm.
Constructing the comparator logic:
The comparator function (a, b) -> bool returns True if a should be higher in the tree than b.
- MinHeap:
a < b (a is smaller, so it goes up).
- MaxHeap:
a > b (a is larger, so it goes up).
Let's trace _sift_up with this comparator.
Current: val. Parent: p_val.
If comparator(val, p_val) is True, swap.
MinHeap: val < p_val -> Swap. Correct.
MaxHeap: val > p_val -> Swap. Correct.
Let's trace _sift_down with this comparator.
Current: val. Children: l_val, r_val.
Find swap_candidate among children.
swap_candidate is the one where comparator(candidate, other_child) is True.
MinHeap: candidate is the smaller one.
MaxHeap: candidate is the larger one.
Then, if comparator(swap_candidate, val) is True, swap.
MinHeap: candidate < val (smaller child is smaller than parent) -> Swap. Correct.
MaxHeap: candidate > val (larger child is larger than parent) -> Swap. Correct.
This abstraction is solid. I will write the code based on this.
Final Code Plan:
- Class
Heap.
__init__: list, comparator.
push, pop, peek.
_sift_up, _sift_down.
- Subclasses
MinHeap and MaxHeap passing lambda a, b: a < b and lambda a, b: a > b.
I will also add type hinting for modern Python practice.
One edge case: Empty heap pop. Raise IndexError.
One edge case: Single element.
The prompt is simple ("Create a min-heap and max-heap implementation"). I should keep the explanation concise and the code clean.
Let's write out the actual response now.
I will create a single Python file structure.
Refinement on sift_down:
We need to check bounds.
left = 2*i + 1. right = 2*i + 2.
If left >= len, stop.
Determine index_to_swap.
Initially index_to_swap = left.
If right < len and comparator(heap[right], heap[left]):
index_to_swap = right.
If comparator(heap[index_to_swap], heap[i]):
swap, recurse/loop.
Looks good.
I'll also briefly mention heapq for production use, but emphasize this implementation is for understanding the data structure.
One last check: Complexity.
Push: O(log n)
Pop: O(log n)
Peek: O(1)
Space: O(n)
Everything is standard.
I will structure the output as:
- Introduction: What a heap is.
- Implementation: A generic class with a comparator.
- Concrete Classes: Min and Max heaps inheriting from it.
- Example Usage: Test code.
Here is a clean, Pythonic implementation of a Heap.
Rather than writing two separate classes with duplicated code, the best practice is to create a generic Heap class that accepts a comparator function. We can then define MinHeap and MaxHeap as subclasses (or simple aliases) that pass in the correct comparison logic.
Implementation
class Heap:
def __init__(self, comparator=lambda x, y: x < y):
"""
Initialize the heap.
:param comparator: A function that returns True if the first argument
has higher priority than the second.
Default is lambda x, y: x < y (Min-Heap).
"""
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):
"""Insert an item into the heap."""
self.heap.append(item)
self._sift_up(len(self.heap) - 1)
def pop(self):
"""
Remove and return the item with the highest priority
(smallest for MinHeap, largest for MaxHeap).
"""
if not self.heap:
raise IndexError("pop from empty heap")
# Swap root with last element
self._swap(0, len(self.heap) - 1)
item = self.heap.pop()
# Restore heap property starting from the new root
if self.heap:
self._sift_down(0)
return item
def peek(self):
"""Return the item with the highest priority without removing it."""
if not self.heap:
raise IndexError("peek from empty heap")
return self.heap[0]
def _swap(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
def _sift_up(self, index):
"""Move the item at index up until 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 _sift_down(self, index):
"""Move the item at index down until heap property is restored."""
size = len(self.heap)
while True:
left_idx = self._left_child(index)
right_idx = self._right_child(index)
candidate_idx = index
# Compare with left child
if left_idx < size and self.comparator(self.heap[left_idx], self.heap[candidate_idx]):
candidate_idx = left_idx
# Compare with right child
if right_idx < size and self.comparator(self.heap[right_idx], self.heap[candidate_idx]):
candidate_idx = right_idx
# If the current node is already in the correct spot, stop
if candidate_idx == index:
break
self._swap(index, candidate_idx)
index = candidate_idx
def __len__(self):
return len(self.heap)
def __str__(self):
return str(self.heap)
# --- Concrete Implementations ---
class MinHeap(Heap):
def __init__(self):
# Use lambda x, y: x < y (x is "better" if it is smaller)
super().__init__(comparator=lambda x, y: x < y)
class MaxHeap(Heap):
def __init__(self):
# Use lambda x, y: x > y (x is "better" if it is larger)
super().__init__(comparator=lambda x, y: x > y)
Example Usage
Here is how you can use the classes above:
# --- Min Heap Example ---
print("--- Min Heap ---")
min_heap = MinHeap()
min_heap.push(10)
min_heap.push(5)
min_heap.push(30)
min_heap.push(2)
print(f"Heap array: {min_heap}") # Internally organized, not strictly sorted
print(f"Peek min: {min_heap.peek()}") # Should be 2
print(f"Popped: {min_heap.pop()}") # 2
print(f"Popped: {min_heap.pop()}") # 5
print(f"Popped: {min_heap.pop()}") # 10
print(f"Popped: {min_heap.pop()}") # 30
# --- Max Heap Example ---
print("\n--- Max Heap ---")
max_heap = MaxHeap()
max_heap.push(10)
max_heap.push(5)
max_heap.push(30)
max_heap.push(2)
print(f"Peek max: {max_heap.peek()}") # Should be 30
print(f"Popped: {max_heap.pop()}") # 30
print(f"Popped: {max_heap.pop()}") # 10
print(f"Popped: {max_heap.pop()}") # 5
print(f"Popped: {max_heap.pop()}") # 2
How it works
- Array Representation: The heap is stored in a standard list (
self.heap). For any node at index i:
- Left Child is at
2*i + 1
- Right Child is at
2*i + 2
- Parent is at
(i - 1) // 2
- Push: Adds the new element to the very end of the list and then performs a Sift Up (swapping with parents) until the heap order is restored.
- Pop: Swaps the root (index 0) with the last element, removes the last element (the original root), and then performs a Sift Down (swapping with the highest priority child) on the new root until order is restored.
- Comparator: The logic relies on a boolean function.
- In a MinHeap, we want to swap if
child < parent.
- In a MaxHeap, we want to swap if
child > parent.
- By passing this logic as a
comparator function, we can reuse the exact same algorithm code for both types.