Kth Largest Element in an Array Leetcode

 Given an integer array nums and an integer k, return the kth largest element in the array.


Note that it is the kth largest element in the sorted order, not the kth distinct element.


Can you solve it without sorting?


 


Example 1:


Input: nums = [3,2,1,5,6,4], k = 2

Output: 5

Example 2:


Input: nums = [3,2,3,1,2,4,5,5,6], k = 4

Output: 4

 

🧠 Idea: Use Min-Heap (PriorityQueue)

We maintain a min-heap of size k. The top (smallest) element of the heap will be the kth largest element.


🔍 First, What is a PriorityQueue (Min-Heap) in Java?

  • It's not a normal list or queue.

  • It stores elements in a heap structure, where the smallest element is always at the top (index 0).

  • It does not maintain insertion order like an array or list.

 Important Point:

When you add elements to a min-heap (like Java's PriorityQueue), Java internally reorganizes them to maintain the heap property.

That means:

  • It doesn’t just add to the start or end.

  • It repositions elements so that the smallest value stays at the root (top).

  • Internally, it’s implemented like a binary heap tree, not like a List.

PriorityQueue<Integer> pq = new PriorityQueue<>();

This creates a Min-Heap Priority Queue, meaning:

  • The smallest number always comes out first.

  • Internally it uses a binary heap, not a sorted list.

PriorityQueue<Integer> pq = new PriorityQueue<>();

pq.add(3);
pq.add(1);
pq.add(5);

pq.poll();  // removes and returns the smallest number

It returns 1 


class Solution {
    public int findKthLargest(int[] nums, int k) {
       
        PriorityQueue<Integer> pq = new PriorityQueue<>();

    for (int num : nums) {
        pq.add(num);
        if (pq.size() > k) {
            pq.poll(); // remove the smallest
        }
    }

    return pq.peek(); // kth largest
    }
}


Step Num Heap (PriorityQueue) Size > k? Action
1 3 [3] No Just add
2 2 [2, 3] No Just add
3 1 [1, 3, 2] ✅ Yes Remove 1 → [2, 3]
4 5 [2, 3, 5] ✅ Yes Remove 2 → [3, 5]
5 6 [3, 5, 6] ✅ Yes Remove 3 → [5, 6]
6 4 [4, 6, 5] ✅ Yes Remove 4 → [5, 6]

📦 Key Methods:

MethodMeaning
add(x)Adds x to the queue
poll()Removes and returns the smallest element
peek()Just looks at the smallest, doesn't remove it
size()Tells how many elements are in the queue

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence