โ† Back to Index

๐Ÿ“š Kth Largest Element in an Array โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Kth Largest Element in an Array problem involves finding the Kth largest element in an unsorted array. This is commonly solved using a min-heap or the Quickselect algorithm.

๐Ÿงฑ Pattern Template

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

        // Step 1: Add elements to the heap
        for (int num : nums) {
            minHeap.offer(num);
            if (minHeap.size() > k) {
                minHeap.poll(); // Remove the smallest element
            }
        }

        // Step 2: The root of the heap is the Kth largest element
        return minHeap.peek();
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Kth Largest Element in an Array

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

Explanation:
- Add elements to the heap and maintain its size as K.
- The 2nd largest element is 5.

๐Ÿ’ก Pro Tips