Back to Heap
Heap
Medium

Find the Kth Largest Integer in the Array

LAB

Given non-negative integers encoded as strings, return the kth largest numeric value as a string.

EXAMPLES

Example 1
Input
{
  "nums": [
    "3",
    "6",
    "7",
    "10"
  ],
  "k": 4
}

Output
"3"

FUNCTION SHAPE

nums: stringArrayk: intstring
SOLUTION NOTE

For kth largest, use a min heap of size k. When heap exceeds size k, pop the smallest. The top of the heap is the kth largest.

Reveal reference solution +
pythonREFERENCE
# Solution 1: Sort
def kthLargestNumber(self, nums: List[str], k: int) -> str:
    nums.sort(key=lambda x: int(x))
    return nums[-k]

# Solution 2: Min heap of size k
def kthLargestNumber(self, nums: List[str], k: int) -> str:
    heap = []
    for num in nums:
        heappush(heap, int(num))
        if len(heap) == k + 1:
            heappop(heap)
    return str(heap[0])
TimeO(n log k)
SpaceO(k)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.