Welcome to Day 7 of your coding interview journey.
Youβve already built a strong foundation:
- β Day 1: HashMaps
- β Day 2: Sliding Window
- β Day 3: Arrays
- β Day 4: Two Pointers
- β Day 5: Interval Problems
- β Day 6: Binary Search
Today, we move into a very powerful and slightly more advanced topic:
π Heaps (Priority Queues)
π§ What is a Heap?
A Heap is a special tree-based data structure that allows you to efficiently get:
- The smallest element (Min Heap)
- The largest element (Max Heap)
In Python, we use:
import heapq
π By default, Python implements a Min Heap
π When Should You Use a Heap?
Look for these patterns:
- βTop Kβ elements
- Kth largest/smallest
- Streaming data
- Priority-based processing
π‘ Problem 1 β Top K Frequent Elements
π§© Problem
Given an array nums, return the k most frequent elements.
β Example
nums = [1,1,1,2,2,3]
k = 2
Output:
[1,2]
π§ Approach β HashMap + Heap
Steps:
- Count frequencies using a HashMap
- Use a heap to get top K elements
π οΈ Solution in Python
import heapq
from collections import Counter
def top_k_frequent(nums, k):
count = Counter(nums)
# Min heap
heap = []
for num, freq in count.items():
heapq.heappush(heap, (freq, num))
if len(heap) > k:
heapq.heappop(heap)
return [num for freq, num in heap]
β‘ Complexity
- Time:
O(n log k) - Space:
O(n)
π― Key Insight
π Keep the heap size at k
This avoids sorting the entire array (O(n log n)).
π‘ Problem 2 β Kth Largest Element in an Array
π§© Problem
Given an array nums, return the kth largest element.
β Example
nums = [3,2,1,5,6,4]
k = 2
Output:
5
π§ Approach β Min Heap of Size K
We maintain a heap of the k largest elements.
π οΈ Solution in Python
import heapq
def find_kth_largest(nums, k):
heap = []
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]
β‘ Complexity
- Time:
O(n log k) - Space:
O(k)
π₯ Alternative (Quickselect β Advanced)
π You can solve this in O(n) average time using Quickselect
But heaps are usually simpler and safer in interviews.
β οΈ Common Mistakes
- β Using full sorting instead of heap
- β Forgetting heap size constraint
- β Confusing min heap vs max heap
- β Not understanding tuple ordering
(freq, num)
π§ͺ Practice Problems
To master heaps, try:
- Merge K sorted lists
- Find median from data stream
- K closest points to origin
- Task scheduler
- Reorganize string
π― Key Takeaways
- Heaps are perfect for:
- Top K problems
- Priority-based tasks
- Optimize from:
- O(n log n) β O(n log k)
- Python tip:
- Use
heapq(Min Heap by default)
- Use
π Your Challenge (Day 7)
Solve this:
Find the K closest numbers to a target in an array.
π Final Thoughts
Heaps are a game-changer for interview problems involving ranking and frequency.
You donβt need to master trees deeply β just understand how to use heaps effectively.