AlgoInsight

DSA problem

Find the Kth Largest Integer in the Array

MediumQuickSort / QuickSelectPattern: QuickSort / QuickSelecttop600AmazonMicrosoftGoogleBloombergAdobe

You are given an array of strings nums and an integer k. Each string in nums represents a non-negative integer without leading zeros. Return the k-th largest integer in nums. Note that duplicate numbers should be counted distinctly — for example, if nums = ["1","2","2"], "2" is the first largest integer and the second largest integer.

The twist compared to the standard "Kth Largest" problem is that the numbers are stored as strings of potentially huge magnitude — up to 100 digits each — far exceeding the range of 64-bit integers. Parsing them into a primitive numeric type is not possible without arbitrary-precision arithmetic, and even where it is (BigInteger in Java, Python int), arithmetic on 100-digit values per comparison can be wasteful.

The crucial insight is that comparing two non-negative integers written in decimal without leading zeros can be done directly on their string representations using a simple two-step rule: first compare by length (a longer string represents a strictly larger number), and only when the lengths are equal do you compare them lexicographically (character by character from the left). This is a strict total order that exactly matches numeric comparison for the given input format.

The canonical optimal approach therefore plugs a string-numeric comparator into Quickselect. We pick the element at index n - k in the order induced by this comparator using a randomized-pivot Lomuto partition, exactly as in the integer version. Each comparison costs O(L) where L is the average string length, so the expected running time is O(n * L) — linear in the total input size — with O(1) extra space and an O(n^2 * L) worst case made vanishingly unlikely by randomized pivot selection.

Examples

Example 1
Input: nums = ["3","6","7","10"], k = 4
Output: "3"
Explanation: Numerically sorted ascending the array is ["3","6","7","10"]. The 4th largest sits at index n - k = 4 - 4 = 0, which is "3".
Example 2
Input: nums = ["2","21","12","1"], k = 3
Output: "2"
Explanation: Numerically sorted ascending the array is ["1","2","12","21"]. The 3rd largest sits at index n - k = 4 - 3 = 1, which is "2". Note that lexicographic order alone would mis-order "12" and "2" — the length-first rule fixes this.
Example 3
Input: nums = ["0","0"], k = 2
Output: "0"
Explanation: Both elements are equal, and the 2nd largest is also "0". Duplicate values count toward the rank distinctly.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraystringquickselectdivide-and-conquersorting

Browse all DSA problems