Find the kth largest number without sorting everything. Quickselect partitions around a pivot, which lands in its final sorted spot, and then keeps only the side that holds index n−k, for O(n) average time and O(1) space.
▼The problem
LeetCode 215 (Medium). Given an integer array nums and an integer k, return the k-th largest element: the k-th in sorted order, not the k-th distinct.
Example (LeetCode's example 1, the walkthrough): [3,2,1,5,6,4], k = 2 → 5, which sits at index n − k = 4 of the sorted row.
The solution
def findKthLargest(nums, k):
target = len(nums) - k
lo, hi = 0, len(nums) - 1
while True:
pivot, store = nums[hi], lo
for j in range(lo, hi):
if nums[j] <= pivot:
nums[store], nums[j] = nums[j], nums[store]
store += 1
nums[store], nums[hi] = nums[hi], nums[store]
if store == target: return nums[store]
if store < target: lo = store + 1
else: hi = store - 1Transcript
Kth Largest Element in an Array. You get a row of numbers and a number k. Return the k-th largest, counting in sorted order, so a repeated value takes a place for each copy.
Take three, two, one, five, six, four, with k two. From the top: six, then five, so the answer is five. Sorted smallest first, five sits at index four: n minus k.
The easy way sorts the whole row and reads index n minus k. That costs n log n, and most of that work orders numbers we never look at.
Quickselect does less. Pick a pivot, here the last number, and partition: numbers no bigger than the pivot move to its left, bigger ones to its right. Now the pivot sits exactly where sorting would put it, though neither side is sorted.
Compare its index with the target. If they match, we're done. If the pivot is left of the target, the answer is on its right, so drop the left side; if it's right, drop the right. Then repeat on what's left.
Let's run it. The target is index four, and the pivot is four. Three, two and one are no bigger; five and six are bigger. The pivot swaps into index three, left of the target, so drop the left side. The new pivot is five. Six is bigger, so five swaps into index four. That's the target: the answer is five.
In code, a store pointer marks where the next small number goes. Each number no bigger than the pivot swaps into that slot, and the pointer moves on. Then the pivot swaps in. Return it if it's the target; otherwise narrow the range and loop.
Each round scans its range once, and a fair pivot halves it: n, plus n over two, plus n over four, about two n in all. That's linear time on average, with constant extra space. A pivot that's always the largest costs n squared; a random pivot makes that unlikely.
Pick a pivot, partition, keep one side. That's Kth Largest Element in an Array.