LeetEye LeetEye
Cheat Sheet

Heap / Priority Queue Cheat Sheet

Quick reference for coding interviews. Bookmark this page!

What is Heap / Priority Queue?

Maintain priority with heap-based data structures.

Trigger Words

When you see these in a problem, think Heap / Priority Queue:

kth largest element in a stream heap last stone weight k closest points to origin kth largest element in an array task scheduler design twitter find median from data stream

Template Code

import heapq

class KthLargest:
    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.heap = nums
        heapq.heapify(self.heap)
        
        while len(self.heap) > k:
            heapq.heappop(self.heap)
    
    def add(self, val: int) -> int:
        heapq.heappush(self.heap, val)
        
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)
        
        return self.heap[0]

Complexity

Typical Time O(log k) per add
Typical Space O(k)

Common Variations

  • Basic Heap / Priority Queue
  • Heap / Priority Queue with constraints
  • Optimized Heap / Priority Queue

Practice Problems

See all Heap / Priority Queue problems →

Practice Heap / Priority Queue

Learn to recognize patterns instantly with interactive MCQs.

Download LeetEye Free
Practice in LeetEye