Find the Kth Largest Integer in the Array

kth-largest where elements are strings of arbitrary length — custom comparator on length then lex.

Medium
Time O(n log k) Space O(k)
LeetCode
5 min read
top-k heaps

Problem#

Given nums of strings representing non-negative integers (no leading zeros), return the kth largest as a string.

Examples#

  • nums = ["3","6","7","10"], k = 4"3"
  • nums = ["2","21","12","1"], k = 3"2"

Constraints#

  • 1 <= nums.length <= 10^4, lengths up to 100.

Approach#

Compare strings numerically without converting to int (they may overflow): longer length wins; equal length, lex order. Use a min-heap of size k.

Solution#

Kth Largest String
class Solution {
public:
string kthLargestNumber(vector<string>& nums, int k) {
auto cmp = [](const string& a, const string& b) {
if (a.size() != b.size()) return a.size() > b.size(); // greater means lower priority in min-heap
return a > b;
};
priority_queue<string, vector<string>, decltype(cmp)> pq(cmp);
for (auto& s : nums) {
pq.push(s);
if ((int)pq.size() > k) pq.pop();
}
return pq.top();
}
};

Editorial#

Lengths up to 100 mean stoll doesn’t suffice — strings encode arbitrarily large integers. The “longer-first” numeric ordering is a primitive worth memorizing: equal length means equal digit count, so lex order coincides with numeric order.

Complexity#

  • Time: O(n log k * L) where L is string length.
  • Space: O(k * L).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.