โ† Back to Index

๐Ÿ“š Find the Kth Largest Integer in the Array โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Find the Kth Largest Integer in the Array problem involves finding the Kth largest integer in an array of strings, where each string represents an integer. The comparison is based on numerical values.

This problem can be solved using a min-heap to track the top K largest integers.

๐Ÿงฑ Pattern Template

class Solution {
    public String kthLargestNumber(String[] nums, int k) {
        PriorityQueue<String> minHeap = new PriorityQueue<>(
            (a, b) -> {
                if (a.length() == b.length()) {
                    return a.compareTo(b); // Lexicographical comparison
                }
                return Integer.compare(a.length(), b.length()); // Compare by length
            }
        );

        // Step 1: Add elements to the heap
        for (String 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 integer
        return minHeap.peek();
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Find the Kth Largest Integer in the Array

Input: nums = ["3","6","7","10"], k = 2
Output: "7"

Explanation:
- The integers are [3, 6, 7, 10].
- The 2nd largest integer is "7".

๐Ÿ’ก Pro Tips