KatInterview

Determine the K-th Highest Score in an Unsorted Array

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searcharrayssortingdivide-and-conquer

Last updated

Find the k-th largest value in an unsorted array of integers without fully sorting the input.

Given an array of unsorted integers nums and a 1-based index k, find the value that would occupy the k-th position if the array were arranged in non-increasing order.

Duplicates are retained and counted as separate positions. For instance, in the sequence [5, 5, 4, 3], the 1st largest value is 5, the 2nd largest value is 5, and the 3rd largest value is 4.

Constraints

  • 1 <= len(nums) <= 2 * 10^5
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= len(nums)

Examples

Example 1

Input: find_kth_largest([3, 2, 1, 5, 6, 4], 2)

Output: 5

Example 2

Input: find_kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)

Output: 4

Example 3

Input: find_kth_largest([7], 1)

Output: 7

Hints

Hint 1

Finding the k-th largest element is equivalent to finding the (len(nums) - k)-th element in 0-indexed ascending order.

Hint 2

Full sorting requires O(n log n) time. Can you use a selection algorithm like Quickselect or a min-heap to improve performance?

Hint 3

To guard against linear worst-case performance on inputs with many identical values or pre-sorted order, implement a 3-way partition (Dutch National Flag) combined with a randomized pivot selection.