Determine the K-th Highest Score in an Unsorted Array
Heaps, Sorting & SearchAuto-graded · 19 test casesLast 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^91 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Finding the $k$-th largest element in an array of size $N$ is equivalent to finding the element at index $N - k$ in a standard non-decreasing sorted order.
While sorting the entire array takes $\mathcal{O}(N \log N)$ time, we can optimize the search to an expected $\mathcal{O}(N)$ runtime using Quickselect (Hoare's Selection Algorithm).
Algorithm Steps
-
Randomized Pivot Selection: Select a pivot randomly from the active segment
[left, right]to prevent worst-case $\mathcal{O}(N^2)$ behavior on pre-sorted or adversarial inputs. -
Three-Way Partitioning (Dutch National Flag Algorithm): Partition the current sub-array into three sections:
- Elements smaller than the pivot:
[left, lt - 1] - Elements equal to the pivot:
[lt, gt] - Elements greater than the pivot:
[gt + 1, right]
Using three-way partitioning handles inputs with heavy duplicate counts efficiently, shrinking the active region dramatically when many duplicate pivots are encountered.
- Elements smaller than the pivot:
-
Narrowing down the Search:
- If the target index
N - kfalls within[lt, gt], the answer is the pivot itself. - If
N - k < lt, recurse/iterative step on the left subarray[left, lt - 1]. - If
N - k > gt, recurse/iterative step on the right subarray[gt + 1, right].
- If the target index
Complexity Analysis
- Time Complexity:
- Expected: $\mathcal{O}(N)$, as each step discards a constant fraction of elements on average.
- Worst Case: $\mathcal{O}(N^2)$, occurring if poor pivots are repeatedly chosen (mitigated by randomized pivot selection).
- Space Complexity: $\mathcal{O}(N)$ to store a shallow copy of the original input array to prevent modifying caller data, and $\mathcal{O}(1)$ additional memory for pointers (iterative implementation).
Reference Solution
import random
from typing import List
def find_kth_largest(nums: List[int], k: int) -> int:
arr = nums[:]
target = len(arr) - k # Convert k-th largest to index in ascending order
rng = random.Random(0)
left, right = 0, len(arr) - 1
while left <= right:
pivot = arr[rng.randrange(left, right + 1)]
lt, i, gt = left, left, right
# 3-way partition around pivot
while i <= gt:
if arr[i] < pivot:
arr[lt], arr[i] = arr[i], arr[lt]
lt += 1
i += 1
elif arr[i] > pivot:
arr[i], arr[gt] = arr[gt], arr[i]
gt -= 1
else:
i += 1
if target < lt:
right = lt - 1
elif target > gt:
left = gt + 1
else:
return pivot
return -1