Kth Largest Element in an Array

Medium#215k largest

You get an array of integers and a number k. Return the k-th largest number: the one that would stand k-th if the array were sorted from largest to smallest. Repeats count, so it is not the k-th distinct value. Our example: [5, 9, 2, 9, 4, 7] and k = 3 — the answer is 7, since the two 9s take first and second place.

input
nums: an array of integers, not sorted, maybe with repeats; k: an integer.
returns
The k-th largest number of nums: the one that would stand at place k if nums were sorted from largest to smallest. Equal numbers count one by one: the 2nd largest of [5, 5, 4] is 5.
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • 1 ≤ k ≤ nums.length
  • −10⁴ ≤ nums[i] ≤ 10⁴
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
function findKthLargest(nums, k) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more heap and top k problems

Pattern “Heap and top K” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.