Heaps (often implemented as Priority Queues) are one of the highest-ROI data structures you can master for technical interviews. Whenever an interviewer asks you to find the "best," "largest," "smallest," or "most frequent" items in a dataset, especially a huge or continuously streaming one, a heap is usually the right tool.
In this guide, we will break down exactly how to identify heap problems, the core template you can apply across multiple languages, and the real-world trade-offs interviewers expect you to discuss.
When to use this pattern
You should immediately consider a heap when you see these signals in a problem statement:
- Keywords: "Top K", "Kth largest/smallest", "K closest", or "Most frequent".
- Streaming data: You are given elements one by one and need to maintain a dynamic property (like the running median or the top 10 scores on a leaderboard).
- Memory constraints: The dataset is too large to fit in RAM (e.g., a 1TB log file), so you cannot use standard sorting algorithms like Quicksort or Merge Sort. A heap allows you to process the data in a single pass while only keeping
Kelements in memory.
The core idea
Counter-intuitively, to find the top K largest elements, you should use a min-heap of size K.
Why? Because the root of a min-heap is always the smallest element in the heap. If you maintain a heap of size K, the root represents the "smallest of the top K largest elements." When a new element arrives, you compare it to the root. If it's larger than the root, it deserves to be in the top K! You pop the root and push the new element.
By keeping the heap size strictly at K, you ensure that the space complexity remains O(K), and each insertion costs at most O(log K).
Template
Here is the foundational template for finding the Top K largest elements in an array. Notice how we push every element into the heap, but immediately pop if the size exceeds K.
import heapq
def top_k_largest(nums, k):
min_heap = []
for num in nums:
heapq.heappush(min_heap, num)
if len(min_heap) > k:
heapq.heappop(min_heap)
return min_heapWorked examples
1. Kth Largest Element in an Array
The Problem: Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Approach: This is the most direct application of our template. We maintain a min-heap of size K. After processing all elements, the smallest element in our top-K heap (which is the root) will be exactly the Kth largest element overall.
import heapq
def findKthLargest(nums, k):
min_heap = []
for num in nums:
heapq.heappush(min_heap, num)
if len(min_heap) > k:
heapq.heappop(min_heap)
return min_heap[0]Complexity:
- Time: O(N log K). We iterate through N elements, and each heap insertion/deletion takes O(log K) time.
- Space: O(K) to store the heap.
2. Top K Frequent Elements
The Problem: Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Approach: First, we need to count the frequencies of all elements using a Hash Map. Then, we use a min-heap of size K to keep track of the most frequent elements. The heap will compare elements based on their frequency, not their actual value.
from collections import Counter
import heapq
def topKFrequent(nums, k):
count = Counter(nums)
min_heap = []
for num, freq in count.items():
heapq.heappush(min_heap, (freq, num))
if len(min_heap) > k:
heapq.heappop(min_heap)
return [num for freq, num in min_heap]Complexity:
- Time: O(N log K). Building the frequency map takes O(N). Inserting unique elements into the heap takes O(U log K) where U is the number of unique elements (U <= N).
- Space: O(N) for the frequency map.
3. Find Median from Data Stream
The Problem: The median is the middle value in an ordered integer list. Implement the MedianFinder class to receive a stream of numbers and return the median in O(1) time.
Approach: This is a classic "Two Heaps" pattern. We divide the data stream into two halves:
- A Max-Heap to store the smaller half of the numbers.
- A Min-Heap to store the larger half of the numbers.
We must maintain two rules:
- Every element in the Max-Heap must be smaller than or equal to every element in the Min-Heap.
- The sizes of the heaps can differ by at most 1. If there's an odd number of elements, we let the Max-Heap hold the extra element.
import heapq
class MedianFinder:
def __init__(self):
self.small = [] # Max-heap (invert values to simulate)
self.large = [] # Min-heap
def addNum(self, num: int) -> None:
# 1. Push to max-heap first
heapq.heappush(self.small, -num)
# 2. Ensure every element in small <= every element in large
if self.small and self.large and (-self.small[0] > self.large[0]):
val = -heapq.heappop(self.small)
heapq.heappush(self.large, val)
# 3. Balance sizes
if len(self.small) > len(self.large) + 1:
val = -heapq.heappop(self.small)
heapq.heappush(self.large, val)
elif len(self.large) > len(self.small):
val = heapq.heappop(self.large)
heapq.heappush(self.small, -val)
def findMedian(self) -> float:
if len(self.small) > len(self.large):
return float(-self.small[0])
return (-self.small[0] + self.large[0]) / 2.0Complexity:
- Time: O(log N) per insertion. Finding the median takes O(1) time.
- Space: O(N) to hold all numbers in the stream.
Variations and pitfalls
When discussing your solution, interviewers will often probe your understanding of alternatives. Be prepared to discuss these trade-offs:
1. Quickselect vs. Heap
For finding the Kth largest element, Quickselect is a popular alternative. It offers an average time complexity of O(N), which is theoretically faster than the heap's O(N log K).
However, Heaps are often preferred because:
- Quickselect modifies the input array. If the array is read-only, you must copy it, costing O(N) space.
- Quickselect has a worst-case time complexity of O(N^2) if the pivots are chosen poorly.
- Quickselect cannot handle streaming data. If you have a stream of 1 billion numbers and want the top 10, a heap requires O(10) memory, whereas Quickselect requires O(1 Billion) memory.
2. Sorting vs. Heap
If you need the top K elements, and K is very close to N (e.g., finding the top 9,999 elements out of 10,000), sorting the entire array might actually be faster in practice.
Sorting takes O(N log N) time, while a heap takes O(N log K). If K ≈ N, the time complexities are asymptotically similar, but sorting algorithms (like Timsort or Introsort) are highly optimized for contiguous memory access and have lower constant factors than maintaining a heap.
Practice checklist
Ready to test your skills? Try applying the heap pattern to these related concepts and problems.