Kth Largest Element

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write kthLargest(nums, k): nums holds 1 to 100,000 whole numbers in any order, possibly repeated, and k is from 1 to the length of nums. Return the kth largest number, counting repeats separately, so in [3, 3, 1] the 1st and 2nd largest are both 3. Don't change nums. For example, kthLargest([3, 2, 1, 5, 6, 4], 2) is 5. The checks include 100,000 numbers with k = 50,000, so finding and removing the largest number k times is too slow: keep a min-heap of the k largest seen so far, or sort a copy.

Your code must pass

  • Finds the kth largest in a small list
  • Counts repeated numbers separately
  • Handles k = 1, k = the length and negative numbers
  • Leaves nums unchanged
  • Is fast enough for 100,000 numbers