Kth Largest Element in a Stream with Min Heap

šŸš€Ā #100DaysOfCode – Day 18 Today’s problem:Ā Kth Largest Element in a StreamĀ šŸ“Š We need to continuously track theĀ kth largest elementĀ as new numbers keep coming in. šŸ”“ Brute Force Approach Store all elements in a list Sort the list every time a new element is added Return the kth largest ā›” Time Complexity:Ā O(n log n)Ā per insertion šŸ‘‰ Not efficient for continuous streams 🟢 Optimized Approach (Min Heap) Use aĀ Min Heap of size k šŸ’” Idea: Keep only theĀ k largest elementsĀ in the heap TheĀ top (peek)Ā will always be the kth largest āœ… Code: class KthLargest { PriorityQueue<Integer> pq = new PriorityQueue<>(); private int k; public KthLargest(int k, int[] nums) { this.k = k; pq = new PriorityQueue<>(k); for (int num : nums) { pq.offer(num); if (pq.size() > k) pq.poll(); } } public int add(int val) { pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek(); } } 🧠 Key Insight šŸ‘‰ Instead of storing all elements, just maintain theĀ top k largest elements If heap size > k → remove smallest The smallest in heap =Ā kth largest overall ⚔ Complexity Time:Ā O(log k)Ā per insertion Space:Ā O(k) šŸ” Example k = 3 Stream: [4, 5, 8, 2] After processing → Heap = [4,5,8] Add(3) → [4,5,8] Add(10) → [5,8,10] šŸ‘‰ kth largest always at the top of heap šŸ’” Learning of the Day When dealing withĀ continuous data streams, don’t store everything — storeĀ only what matters. #Day18 #100DaysOfCode #DSA #Java #Heap #PriorityQueue #CodingJourney #LeetCode

To view or add a comment, sign in

Explore content categories