DSA Notes
Master the most common heap-based interview problems: Kth largest element, merge K sorted lists, find median in a stream, and top K frequent elements.
Why Heaps in Interviews?
Heap problems test whether you can identify when partial ordering is sufficient — you do not need full sorting. Whenever a problem asks for "the Kth something," "top K," or "streaming minimum/maximum," your mind should immediately jump to heaps. Let's dive into the four most important patterns.
Problem 1: Kth Largest Element in an Array
Problem: Given an unsorted array, find the Kth largest element. For example, in [3,2,1,5,6,4] with K=2, the answer is 5.
Approach 1: Sort and Index — O(n log n)
The simplest approach. Sort descending and return index K-1. Works but does more work than necessary.
Approach 2: Min-Heap of Size K — O(n log K)
This is the elegant heap solution. Maintain a min-heap of exactly K elements. After processing all elements, the heap root is the Kth largest:
Why this works: The min-heap of size K always contains the K largest elements seen so far. The smallest among those K elements (the root) is by definition the Kth largest overall.
Space: O(K). If K is small relative to N, this is much better than sorting.
Approach 3: QuickSelect — O(n) Average
Based on the partition step of QuickSort. Average O(n) but worst case O(n²). In practice, randomized QuickSelect is often the fastest:
Problem 2: Merge K Sorted Lists
Problem: Given K sorted linked lists, merge them into one sorted list.
Approach: Min-Heap of K Elements — O(N log K)
At any point, we only need to compare the current heads of all K lists. A min-heap of size K does this efficiently:
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_k_lists(lists):
heap = []
# Initialize heap with head of each list
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))
dummy = ListNode(0)
current = dummy
while heap:
val, idx, node = heapq.heappop(heap)
current.next = node
current = current.next
if node.next:
heapq.heappush(heap, (node.next.val, idx, node.next))
return dummy.nextKey insight: The idx parameter prevents comparison of ListNode objects when values are equal. The heap never exceeds size K, so each push/pop is O(log K). With N total nodes, the total time is O(N log K).
Alternative approaches:
- Merge lists pairwise (like merge sort): O(N log K) time but simpler code
- Concatenate all and sort: O(N log N) — worse when K << N
Problem 3: Find Median in a Data Stream
Problem: Design a data structure that supports addNum(num) and findMedian() for a continuous stream of numbers.
The Two-Heap Technique
This is a beautiful pattern. Maintain two heaps:
- max-heap (left half): stores the smaller half of numbers
- min-heap (right half): stores the larger half of numbers
The median is either the top of the max-heap (odd count) or the average of both tops (even count).
Complexity: addNum is O(log n), findMedian is O(1). Space is O(n).
Why two heaps? The median divides data into two equal halves. If we maintain each half in a heap with the "extremes" facing each other (max of left half, min of right half), the median is always accessible at the tops.
Problem 4: Top K Frequent Elements
Problem: Given an array, return the K most frequent elements. For [1,1,1,2,2,3] with K=2, return [1,2].
Approach 1: Heap — O(n log K)
Count frequencies, then use a min-heap of size K to keep the top K:
Approach 2: Bucket Sort — O(n)
Since frequencies range from 1 to n, we can use bucket sort:
Pattern Recognition Guide
| Problem Signal | Technique | Heap Type |
|---|---|---|
| "Kth largest/smallest" | Size-K heap | Min-heap for Kth largest |
| "Top K" elements | Size-K heap | Min-heap (keeps K largest) |
| "Merge K sorted" | Size-K heap | Min-heap of heads |
| "Running median" | Two heaps | Max-heap + Min-heap |
| "Closest K points" | Size-K heap | Max-heap by distance |
| "Schedule/intervals" | Event processing | Min-heap by end time |
Practice Problems (by difficulty)
- Easy: Last Stone Weight — max-heap simulation
- Medium: K Closest Points to Origin — min-heap with distance
- Medium: Task Scheduler — greedy with max-heap for frequencies
- Medium: Reorganize String — max-heap to alternate characters
- Hard: Sliding Window Median — two heaps with lazy deletion
- Hard: IPO (LeetCode 502) — two heaps for capital management
Tips for Interviews
- State your approach clearly: "I'll use a min-heap of size K because I only need the K largest elements, and the min-heap root will be my answer."
- Know your language's API: Python's
heapqis min-heap only. Java hasPriorityQueue. C++ haspriority_queue(max by default). - Watch for tiebreakers: When heap elements might be equal, add a sequence number to avoid comparison errors.
- Consider space: A size-K heap uses O(K) space — mention this as an advantage over sorting.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Heap Interview Problems.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, heaps, heap, problems
Related Data Structures & Algorithms Topics