Menu
CoddyTech

Kth Largest Element in an Array

MediumHeapSortingpython iconjava iconcpp iconc iconjs icon+10

You get an array of integers nums and an integer k. Return the k-th largest value in nums: the value at position k, counting from 1, once the array is sorted from largest to smallest.

Equal values count separately. In [5, 5, 1] the largest value is 5 and the second largest is also 5.

Function

findKthLargest(nums: integer-array, k: integer) → integer
numsinteger-array
the values to rank
kinteger
which largest value to return, 1 for the largest
Returnsinteger
the k-th largest value, counting duplicates

Constraints

  • 1 ≤ k ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • Equal values count as separate values.

Examples

Input
nums = [7, 2, 9, 4, 9, 1]k = 2
Output
9
Explanation
From largest to smallest the values are 9, 9, 7, 4, 2, 1. The two 9s count separately, so the second largest is 9, not 7.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Values now arrive one at a time. Can you report the median of all values seen so far after each arrival, in O(log n) time per value?

Reset code
def findKthLargest(nums, k):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [7, 2, 9, 4, 9, 1]
k = 2

Expected

9