Solved LeetCode 703 with Java PriorityQueue for kth largest element

🎉 Day 400 of #500DaysOfCode 🎉 Today I tackled an interesting problem from LeetCode — “703. Kth Largest Element in a Stream”. The task: Build a class that maintains a stream of scores (or numbers) and, for a given integer k, always returns the kth largest element after each insertion. Why this is cool: Real-world analogy: Think of a university admissions office tracking the kth highest test score dynamically as new applicants submit scores. Efficient solution involves a min-heap (priority queue) of size k — keep only the top k largest elements; the root is then the kth largest overall. Good practice for streaming data, heaps, and understanding dynamic order statistics. 🔧 My Java solution uses PriorityQueue<Integer>: Initialize with k and the initial array of scores. On each .add(val) call: insert value, if heap size > k then remove the smallest, then peek to get the kth largest. Time complexity: O(log k) per addition. Space: O(k). ✅ Key takeaways: Using a min-heap of fixed size is a neat way to get the kth largest in a stream. Make sure to prune the heap so it never grows beyond k. Good addition to my toolkit for streaming / dynamic order problem types. What’s next: On to Day 401 — I’ll be diving into [insert upcoming topic or type: e.g., “graph algorithms”, “dynamic programming advanced”, “system design mini challenge”]. #500DaysOfCode #CodingChallenge #LeetCode #Java #DataStructures #Algorithms #Heap #PriorityQueue #ProblemSolving #DeveloperJourney

  • graphical user interface, text

“Legends aren’t born, they’re built — and you’re proof! 🏆” Abhijeet Sinha

To view or add a comment, sign in

Explore content categories