Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-022

Kth Largest Element via Heap

Problem

Return the k-th largest element of a list, where k is 1-based.

Maintain a min-heap of at most k elements: push each number and whenever the heap grows past k, pop the smallest. The root of the final heap is the k-th largest element.

You may use the heapq module. k is always between 1 and len(nums).

Hint

A min-heap of size k keeps the k largest values seen so far; its root is the smallest of them.

Test cases

case 1
in: [[3,2,1,5,6,4],2]
expected: 5
case 2
in: [[3,2,3,1,2,4,5,5,6],4]
expected: 4
case 3
in: [[1],1]
expected: 1
case 4
in: [[-5,-2,-9],2]
expected: -5
Starter codePython
def kth_largest(nums, k):
    # Your code here
    pass

4 test cases · run your code against them in the editor