Kth Largest Element
Picture
To find the second largest in [3,2,1,5,6,4], fully sorting every relationship is extra work.
Predict
After the pivot lands on the target rank, must its sides be sorted?
Walk through the small example
No. Partition fixes one rank; only one remaining side can contain the desired rank.
Mental model and complete Python solution
Translate kth largest into sorted index n-k. Partition around a pivot. The pivot’s final index tells whether to stop or discard one whole side.
What the function promises: Return the kth largest value, with k starting at one. Mutates the list. Raise ValueError for invalid k.
def kth_largest(values, k):
if not 1 <= k <= len(values):
raise ValueError("Invalid k")
target, left, right = len(values) - k, 0, len(values) - 1
while True:
pivot, boundary = values[right], left
for scan in range(left, right):
if values[scan] <= pivot:
values[boundary], values[scan] = values[scan], values[boundary]
boundary += 1
values[boundary], values[right] = values[right], values[boundary]
if boundary == target:
return values[boundary]
if boundary < target:
left = boundary + 1
else:
right = boundary - 1
assert kth_largest([3,2,1,5,6,4], 2) == 5
Work and storage: Average O(n), worst-case O(n²), O(1) auxiliary storage.
When to recognize it: Partition fixes one rank; only one remaining side can contain the desired rank.
Check before applying it: Deterministic poor pivots can make quadratic work, and mutation may be unacceptable.
Change one rule
Values arrive one at a time and cannot all be stored.
See what changes
Maintain a min-heap of the largest k values seen.
Connect
Quicksort: partition around a pivot: Reuse the same partition invariant.
Heap: keep the next extreme ready: A bounded heap is useful when values stream or k is small.