↻one more pass.
Heaps · Medium

Kth Largest Element In An Array: the idea to remember.

Return the kth largest array value, counting duplicate values separately.

Solve on LeetCode ↗

The core insight

Keep a min heap containing at most the k largest values processed so far.

Why it works

Discarding the smallest whenever the heap exceeds k preserves the k greatest candidates; its root is the kth largest.

The mistake to avoid

Duplicates count toward the rank. Use a min heap of size k rather than removing k elements from a min heap of all values.

Time: O(n log(k+1))Space: O(k)

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).
// Partition around a pivot and continue only into the side containing the target rank.
public int findKthLargest(int[] nums, int k) {

    PriorityQueue<Integer> heap = new PriorityQueue();


    for (int n : nums) {

        heap.add(n);

        if (heap.size() > k) {

            heap.poll();
        }
    }

    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.