1. Introduction to Heaps
Heaps provide O(1) peek and O(log n) insertion/deletion for priority management. Below are 20 essential questions with complete solutions in C++, Java, Python, and JavaScript.
2. Core Heap Questions
Q1. Kth Largest Element in an Array
cppint findKthLargest(vector<int>& nums, int k) { priority_queue<int, vector<int>, greater<int>> minHeap; for (int num : nums) { minHeap.push(num); if (minHeap.size() > k) minHeap.pop(); } return minHeap.top(); }
javapublic int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for (int num : nums) { minHeap.add(num); if (minHeap.size() > k) minHeap.poll(); } return minHeap.peek(); }
pythonimport heapq def findKthLargest(nums: list, k: int) -> int: min_heap = [] for num in nums: heapq.heappush(min_heap, num) if len(min_heap) > k: heapq.heappop(min_heap) return min_heap[0]
javascriptfunction findKthLargest(nums, k) { nums.sort((a, b) => b - a); return nums[k - 1]; }
Time Complexity: O(n log k) | Space Complexity: O(k)
3. Summary Table
| Problem | Technique | Time | Space |
|---|---|---|---|
| Kth Largest | Min Heap of Size K | O(n log k) | O(k) |
Practice all heap problems on DSAMaster's practice platform.
