Kth Largest Element in Array with Min Heap

🚀 #100DaysOfCode – Day 20 Today’s problem: Kth Largest Element in an Array 📊 Given an integer array nums and an integer k, return the kth largest element in the array (not necessarily distinct). 🔴 Brute Force Approach Sort the array in descending order Return the element at index k-1 ⛔ Time Complexity: O(n log n) 👉 Sorting the entire array is unnecessary when we only need one element 🟢 Optimized Approach (Min Heap) 💡 Idea: Use a Min Heap of size k Keep only the k largest elements The top of the heap will always be the kth largest ✅ Code: class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size() > k) { pq.poll(); } } return pq.peek(); } } 🧠 Key Insight 👉 Instead of sorting everything, maintain only the k largest elements If heap size exceeds k → remove smallest The smallest in heap = kth largest overall ⚡ Complexity Time: O(n log k) Space: O(k) 🔍 Example nums = [3,2,1,5,6,4], k = 2 Step-by-step heap: Add → maintain size k 👉 Final heap → [5,6] 👉 Answer = 5 💡 Learning of the Day When solving problems: 👉 Don’t process everything — process only what’s required #Day20 #100DaysOfCode #DSA #Java #Heap #PriorityQueue #CodingJourney #LeetCode #ProblemSolving

To view or add a comment, sign in

Explore content categories