Locate the K-th Dominant Value
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Find the k-th largest integer in an unsorted list efficiently using quickselect or priority queues.
Given an unsorted array of integers a and an integer k, determine the $k$-th largest value present in the array.
Note that this refers to the $k$-th value when sorted in non-decreasing order ( counting duplicate values separately), rather than the $k$-th unique entry.
Constraints
- $1 \le k \le \text{len}(a) \le 10^5$
- $-10^4 \le a[i] \le 10^4$
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
Hints
Hint 1
Think about how finding the k-th largest element relates to finding an element at a specific index in a sorted list.
Hint 2
Full sorting takes O(n log n) time. Can you use a min-heap of size k to do better?
Hint 3
Can you apply a quickselect partitioning scheme to reach average linear time complexity?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Finding the $k$-th largest value in an array of size $n$ is mathematically equivalent to locating the element at zero-based index n - k in the fully sorted array.
While sorting the entire collection requires $O(n \log n)$ time, we can optimize this task using Quickselect or a Min-Heap:
-
Quickselect Strategy (Average $O(n)$):
- Select a pivot value (e.g., using median-of-three to safeguard against structured inputs).
- Partition the sub-array into two sides: values less than the pivot on the left and values greater than the pivot on the right using standard two-pointer partitioning (Hoare's method).
- Check which side contains the target index (
n - k). - Recursively or iteratively shrink the active range to only the side containing the target index.
-
Min-Heap Strategy ($O(n \log k)$):
- Iterate through the list, maintaining a min-heap containing the $k$ largest elements seen so far.
- If the heap exceeds size $k$, pop the smallest element.
- At the end, the top of the min-heap will hold the $k$-th largest element.
Complexity Analysis
- Time Complexity: Average $O(n)$ using Quickselect (worst-case $O(n^2)$ if poor pivots are chosen). Using a heap takes $O(n \log k)$ time.
- Space Complexity: $O(n)$ to avoid modifying the input array (or $O(k)$ for the min-heap approach).
Python Source Code
from typing import List
def find_kth_largest(a: List[int], k: int) -> int:
values = a[:]
target = len(values) - k
left, right = 0, len(values) - 1
while left <= right:
mid = (left + right) // 2
trio = sorted((values[left], values[mid], values[right]))
pivot = trio[1] # Median-of-three selection
i, j = left, right
while i <= j:
while values[i] < pivot:
i += 1
while values[j] > pivot:
j -= 1
if i <= j:
values[i], values[j] = values[j], values[i]
i += 1
j -= 1
if target <= j:
right = j
elif target >= i:
left = i
else:
return values[target]
return values[target]