Loading section...
Heap with Tuples: Priority and Tie-Breaking
Concepts: pyHeapTuples, pyTieBreaking, pyIterToolsCount
Python heaps compare tuples lexicographically: first by the first element, then by the second if there is a tie, then by the third. This is incredibly useful for priority queues where you want to order by one field and break ties by another. It is also a gotcha: if two tuples have the same priority value and the second element is an uncomparable type (like a custom object without __lt__), heapq will raise a TypeError. Knowing this cold is how you avoid a humiliating bug in a live interview. Priority Queue with (priority, item) Tuples The (priority, counter, item) pattern is the canonical safe way to use heaps with tuples. The counter guarantees that no two tuples ever have the same first two elements, which means heapq never needs to compare the item directly. Without the counter, if two t