Skip to main content
Heap Pattern

What is Heap?

Heap is a complete binary tree that maintains the heap property: parent is always smaller (min-heap) or larger (max-heap) than children. It provides O(log n) insertion and O(1) access to min/max.
Quick Recognition: If you need k largest/smallest, merge sorted lists, or continuously find min/max, think Heap!

Pattern Recognition Checklist

Use Heap When

  • Need k largest/smallest elements
  • Merge k sorted lists/arrays
  • Continuously track min/max
  • Priority-based processing
  • Median from data stream

Don't Use When

  • Need sorted order (use sort)
  • Need arbitrary access by index
  • Single min/max needed once
  • Memory is very constrained

When to Use

Top K Elements

Find k largest/smallest elements

Merge K Lists

Merge multiple sorted sequences

Scheduling

Process by priority, deadlines

Median Finding

Running median with two heaps

Pattern Variations

1. Kth Largest Element

2. Top K Frequent Elements

3. Merge K Sorted Lists

4. Find Median from Data Stream

5. K Closest Points to Origin

Classic Problems

Pattern: Min-heap of size kKey: Top of min-heap is kth largest after processing all
Pattern: Min-heap of list headsKey: Always pop smallest, push its next element
Pattern: Two heaps (max for small, min for large)Key: Keep heaps balanced, median from tops
Pattern: Max-heap for most frequent tasksKey: Process most frequent first with cooldown

Common Mistakes

Avoid These Pitfalls:
  1. Wrong heap type: Min-heap for k largest, max-heap for k smallest
  2. Python max-heap: Use negative values with heapq
  3. Heap size management: Pop when size exceeds k
  4. Custom comparators: Be careful with lambda syntax in each language

The Counter-Intuitive Heap Choice

This confuses many beginners:

Complexity Quick Reference

Interview Problems by Company

Interview Tips

Script for interviews:
  1. “Since I need the k largest, I’ll use a min-heap of size k.”
  2. “I’ll iterate through all elements, pushing each to the heap.”
  3. “When heap size exceeds k, I pop the smallest.”
  4. “After processing all, the heap contains the k largest.”
  5. “Time is O(n log k), space is O(k).”
Python’s heapq is a min-heap only. For max-heap:
For custom objects, use tuples: (priority, item)

Practice Problems

Practice Roadmap

1

Day 1: K Elements

  • Solve: Kth Largest Element, Top K Frequent
  • Focus: When to use min vs max heap
2

Day 2: Merging

  • Solve: Merge K Sorted Lists, K Pairs with Smallest Sum
  • Focus: Multi-source merging
3

Day 3: Two Heaps

  • Solve: Find Median from Data Stream
  • Focus: Balancing two heaps
4

Day 4: Applications

  • Solve: Task Scheduler, Meeting Rooms II
  • Focus: Scheduling with heaps
Interview Tip: For “k largest/smallest” problems, think heap. Use opposite heap type to maintain window of k elements.