Kth Largest Element In a Stream: the idea to remember.
Maintain the kth largest value as integers are added to a stream.
The core insight
Keep only the k largest values seen; their minimum is the kth largest once k values exist.
Why it works
Any discarded value is smaller than at least k retained values and cannot affect the current kth largest.
The mistake to avoid
Duplicates count as separate elements. Heap size is k, not the entire stream.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Keep only the k largest values seen; their minimum is the kth largest once k values exist.
class KthLargest {
final PriorityQueue<Integer> heap = new PriorityQueue<>();
final int k;
public KthLargest(int k, int[] nums) {
this.k = k;
for (int n : nums) add(n);
}
public int add(int val) {
if (heap.size() < k) heap.offer(val);
else if (val > heap.peek()) {
heap.poll();
heap.add(val);
}
return heap.peek();
}
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.