Min Heap¶
py_ds.datastructures.heaps.MinHeap
¶
Bases: Heap
A min-heap implementation.
In a min-heap, the parent node is always less than or equal to its children. The root element is the minimum value in the heap.
Initialize the heap with optional items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[T] | None
|
Optional iterable of items to initialize the heap with. If None, creates an empty heap. |
None
|
Source code in src/py_ds/datastructures/heaps.py
Functions¶
push
¶
Add an item to the heap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to add to the heap. |
required |
Time complexity: O(log n) where n is the number of elements.
Source code in src/py_ds/datastructures/heaps.py
pop
¶
Remove and return the root element of the heap.
Returns:
| Type | Description |
|---|---|
T
|
The root element of the heap (minimum for MinHeap, maximum for MaxHeap). |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the heap is empty. |
Time complexity: O(log n) where n is the number of elements.
Source code in src/py_ds/datastructures/heaps.py
peek
¶
Return the root element without removing it.
Returns:
| Type | Description |
|---|---|
T
|
The root element of the heap (minimum for MinHeap, maximum for MaxHeap). |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the heap is empty. |
Time complexity: O(1).
Source code in src/py_ds/datastructures/heaps.py
__len__
¶
Return the number of elements in the heap.
Returns:
| Type | Description |
|---|---|
int
|
The number of elements in the heap. |
Time complexity: O(1).
__bool__
¶
Return the truthiness of the heap.
Returns:
| Type | Description |
|---|---|
bool
|
False if the heap is empty, True otherwise. |
Enables: if heap: ...