• Interview Preparation
  • πŸš€ Code Day 7 – Heaps (Top K Problems Made Easy)

    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:

    1. Count frequencies using a HashMap
    2. 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:

    1. Merge K sorted lists
    2. Find median from data stream
    3. K closest points to origin
    4. Task scheduler
    5. 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)

    πŸš€ 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.

    3 mins