iq.lab
Python starts when a code cell comes near or you run one
mediumHeaps target 25 min

Kth largest number

You get a list of integers nums and a number k. Return the kth largest number: the one at position k, counting from 1, if nums were sorted from largest to smallest.

Repeated values count separately. In [5, 5, 4] the second largest is 5, not 4.

Example 1
Inputnums = [7, 2, 9, 4, 5], k = 2Output7

Sorted from largest: 9, 7, 5, 4, 2. Position 2 holds 7.

Example 2
Inputnums = [6, 3, 6, 1, 6, 2], k = 3Output6

Sorted from largest: 6, 6, 6, 3, 2, 1. The three 6s fill positions 1 to 3.

Example 3
Inputnums = [-5, -1, -8], k = 3Output-8

When k is the length of the list, the answer is the smallest number.

Constraints
  • 1 ≤ k ≤ len(nums) ≤ 105

  • -105 ≤ nums[i] ≤ 105

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.