☰ All problems

48. Kth Largest Element in an Array

MediumArrayHeapSorting

Given an integer array nums and an integer k, return the k-th largest element: the value that would be at position k (1-indexed) if the array were sorted in descending order.

Duplicates count separately. In [4,4,1], both the 1st and 2nd largest are 4.

Can you beat sorting the whole array?

Example 1
Input: nums = [7,1,5,3,9], k = 2
Output: 7

Explanation: Sorted descending: 9, 7, 5, 3, 1. The second value is 7.

Example 2
Input: nums = [4,4,1,4,2], k = 3
Output: 4

Explanation: Sorted descending: 4, 4, 4, 2, 1. Repeated values each take a position.

Example 3
Input: nums = [-3], k = 1
Output: -3

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
💡 Hint 1

Sorting gives an easy O(n log n) answer. Do you really need the whole array in order?

💡 Hint 2

Keep a min-heap of the k largest values seen so far. When it grows past k, pop the smallest. The heap top is the answer at the end: O(n log k).

💡 Hint 3

Quickselect partitions around a pivot like quicksort, but only continues into the side that contains the target index. With a random pivot this averages O(n).

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
function findKthLargest(nums, k) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc