Practice · Heap · 4 of 5

Kth Largest Number in a List

You are given a list of integers nums and an integer k. Return the k-th largest value: the value that would sit at position k (counting from 1) if nums were sorted from largest to smallest.

Equal values count separately, so in [5, 5, 1] the largest and the second largest are both 5. Try to do better than sorting the whole list.

Example 1

Input
nums = [4, 9, 1, 7, 3], k = 2
Output
7
From largest down the values are 9, 7, 4, 3, 1, and the second is 7.

Example 2

Input
nums = [6, 2, 6, 5, 1], k = 2
Output
6
The two 6s count separately, so the second largest is 6 as well.

Constraints

  • 1 ≤ k ≤ length of nums ≤ 10⁵
  • Every value is between −10⁴ and 10⁴.
Brush up firstHeap visualiser