Find the Kth Largest Integer in the Array - Problem

You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.

Return the string that represents the kth largest integer in nums.

Note: Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], "2" is the first largest integer, "2" is the second-largest integer, and "1" is the third-largest integer.

Input & Output

Example 1 — Basic Case
$ Input: nums = ["3","6","7","10"], k = 4
Output: "3"
💡 Note: Sorted in descending order: ["10","7","6","3"]. The 4th largest is "3".
Example 2 — With Duplicates
$ Input: nums = ["2","21","12","1"], k = 3
Output: "2"
💡 Note: Sorted: ["21","12","2","1"]. The 3rd largest is "2".
Example 3 — Large Numbers
$ Input: nums = ["1","2","2"], k = 2
Output: "2"
💡 Note: Sorted: ["2","2","1"]. Both "2"s are counted distinctly, so 2nd largest is "2".

Constraints

  • 1 ≤ k ≤ nums.length ≤ 104
  • 1 ≤ nums[i].length ≤ 100
  • nums[i] consists of only digits
  • nums[i] will not have any leading zeros

Visualization

Tap to expand
Find the Kth Largest Integer in Array Custom String Comparator Approach INPUT Array of String Numbers: "3" "6" "7" "10" [0] [1] [2] [3] k = 4 (4th largest) Input Values: nums = ["3","6","7","10"] k = 4 Numbers stored as strings (can be very large) ALGORITHM STEPS 1 Custom Comparator Compare by length first, then lexicographically 2 Sort Descending Sort array from largest to smallest After sorting (desc): "10" "7" "6" "3" 3 Access Index k-1 Return element at position (k-1) = 3 4 Return Result sorted[3] = "3" is 4th largest 1st 2nd 3rd 4th FINAL RESULT Sorted Array (Descending): "10" "7" "6" "3" 1st 2nd 3rd 4th OUTPUT "3" 4th Largest Integer OK - Verified 10 > 7 > 6 > 3 Key Insight: When comparing large numbers as strings, compare by LENGTH first (longer = bigger), then LEXICOGRAPHICALLY for same-length strings. This avoids integer overflow issues! Time: O(n log n) for sorting | Space: O(n) for sorted array TutorialsPoint - Find the Kth Largest Integer in the Array | Custom String Comparator Approach
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
23.5K Views
Medium Frequency
~25 min Avg. Time
891 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen