Interview challenge · medium · array, heap, quickselect
Kth Largest Element in an Array
The challenge
Given an unsorted array of integers and a number k, return the k-th largest element: the one that would sit in position k if the array were sorted from largest to smallest. Duplicates count as separate elements. Sorting works in O(n log n); can you do better?
Example
[3, 2, 1, 5, 6, 4], k = 2 -> 5
[3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 -> 4 (6, 5, 5, 4)Idea: quickselect. Pick a pivot (here, the last element of the range) and partition: everything bigger than the pivot moves to its left, and the pivot lands in its final place, i. Now it is the (i + 1)-th largest. If that is k, you are done; if not, the answer is only on one side, so keep partitioning that side and forget the other. On average each round halves the work: O(n) time, O(1) extra space. A sorted input with this pivot is the worst case, O(n²); a random pivot avoids it in practice. Another common answer is a min-heap that keeps the k largest seen so far: O(n log k).
The solution
# Kth Largest Element - ayotl.dev
def kth_largest(a, k):
# quickselect: keep only one side
lo, hi = 0, len(a) - 1
while True:
# bigger than the pivot go left
p, i = a[hi], lo
for j in range(lo, hi):
if a[j] > p:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
# pivot is the (i+1)-th largest
if i == k - 1:
return a[i]
if i < k - 1:
lo = i + 1 # look right
else:
hi = i - 1 # look left
a = [3, 2, 1, 5, 6, 4]
b = [3, 2, 3, 1, 2, 4, 5, 5, 6]
print(kth_largest(a, 2))
print(kth_largest(b, 4))
$ python3 kth_largest_element_in_an_array.py
5
4