From 247995bf280b2c5b0a427ec686535ccc9281c208 Mon Sep 17 00:00:00 2001 From: Jay Pokale Date: Tue, 24 Nov 2026 12:08:06 +0530 Subject: [PATCH] Fix binomial heap losing track of the minimum when values are equal --- data_structures/heap/binomial_heap.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/data_structures/heap/binomial_heap.py b/data_structures/heap/binomial_heap.py index 489355ee7271..f84e96f35686 100644 --- a/data_structures/heap/binomial_heap.py +++ b/data_structures/heap/binomial_heap.py @@ -179,7 +179,11 @@ def merge_heaps(self, other): next_node = i.parent.parent # Merging trees + pair = (i, i.parent) i = i.merge_trees(i.parent) + # With equal values the old min_node can lose its place as a root + if self.min_node in pair: + self.min_node = i # Updating links i.left = previous_node @@ -237,7 +241,11 @@ def insert(self, val) -> None: next_node = self.bottom_root.parent.parent # Merge + pair = (self.bottom_root, self.bottom_root.parent) self.bottom_root = self.bottom_root.merge_trees(self.bottom_root.parent) + # With equal values the old min_node can lose its place as a root + if self.min_node in pair: + self.min_node = self.bottom_root # Update Links self.bottom_root.parent = next_node @@ -257,6 +265,14 @@ def is_empty(self) -> bool: def delete_min(self): """ delete min element and return it + + >>> heap = BinomialHeap() + >>> for value in [4, 1, 8, 2, 2]: + ... heap.insert(value) + >>> heap.delete_min(), heap.delete_min(), heap.peek() + (1, 2, 2) + >>> heap.delete_min(), heap.delete_min(), heap.delete_min() + (2, 4, 8) """ # assert not self.isEmpty(), "Empty Heap"