Skip to content
DSAPrep

    ↑↓ to move · Enter to open · Esc to close

    ← All patterns

    Heap / Priority Queue

    Always get the smallest (or largest) item in O(log n).

    Reach for it when

    • Top K / K-th largest / K closest
    • Merge K sorted streams
    • Repeatedly process the cheapest or earliest item (scheduling)

    Core idea

    A heap keeps the minimum at the root with O(log n) push and pop. For top-K largest, keep a min-heap of size K: the root is the weakest member and is evicted when something better arrives. Two heaps (max-heap low half, min-heap high half) maintain a running median.

    Template · O(n log k) time, O(k) space

    import heapq
    def k_largest(nums, k):
    heap = [] # min-heap of the k best
    for x in nums:
    heapq.heappush(heap, x)
    if len(heap) > k:
    heapq.heappop(heap) # evict the weakest
    return heap[0] # k-th largest

    Common pitfalls

    • Python heapq is a min-heap: negate values for a max-heap
    • Push tuples (priority, tiebreak, item) when items are not comparable

    Practice · 0 / 8 done