Kth Largest Element in an Array
Find the value that would sit k-th from the end of the sorted array, without sorting the whole array.
You are given an array of integers numsk
Example 1
Output: 5
Explanation: sorted, the array is [1, 2, 3, 4, 5, 6]. The largest value is 6 and the second largest is 5.
Example 2
Output: 4
Explanation: sorted, the array is [1, 2, 2, 3, 3, 4, 5, 5, 6]. Counting from the end gives 6, 5, 5 and then 4. The two 5s take two places.
The Idea
Picture a pile of test scores, in the order the papers were handed in. Rank them from best to worst, and the k-th largest score is the one in place k: k = 1k = 2nums
Look at Example 1 again. Sorted, the array is [1, 2, 3, 4, 5, 6]. Reading from the right, 6 comes first and 5 second, so the answer for k = 2
Sorting finds the answer, but it puts every value in its place, and we only read one of them. Could we put a single value in its sorted place, and still tell on which side of it the answer lies?
We can. Pick one value, called the pivot, and move every smaller value to its left and every other value to its right. This rearranging is called partitioning. Afterwards, the values before the pivot are exactly the ones smaller than it, so the pivot sits at the same index as in the sorted array.
Look at the picture. The pivot is the last value, 4, in orange. After partitioning, 3, 2 and 1 are on its left, 6 and 5 are on its right, and 4 has landed at index 3. That is where 4 is in the sorted array [1, 2, 3, 4, 5, 6]. The two sides are not sorted inside, since 6 still comes before 5, but nothing needs them to be.
Now compare index 3 with the target, index 4. The target is to the right of the pivot, so the answer must be 6 or 5, and the left part can be forgotten. Partitioning just [6, 5] around its last value, 5, puts 5 at index 4. That is the target, so the answer is 5.
So the array never gets fully sorted. Each partition puts one value in its final place and drops the side that cannot hold the answer. Repeating this on the remaining side until the pivot lands on the target is called Quickselect.
Solution Approach
Turning that idea into code means settling four things: which index to look for, how to partition a range, how to narrow the search, and how to pick the pivot.
The index to look for
Why not simply sort? Arrays.sort(nums)nums[n - k]
Quickselect looks for the same index, target = n - kk - 1
Partitioning a range
How do the smaller values get to the left? The pivot is the last value of the range. A second index, storestorestore
In Example 1, 3, 2 and 1 are each smaller than 4. Each swaps with itself, since it is already at storestorestore
A value equal to the pivot is not smaller, so it stays on the right. The pivot still lands at a correct sorted index, because equal values can sit in either order.
Narrowing the search
Which part gets partitioned next? Two indexes, leftright
Each round drops at least the pivot itself, so the loop always ends. Since only one side is kept, a plain loop is enough, with no recursion.
Choosing the pivot
Taking the last value as the pivot is simple, and works well on values in random order. It goes badly when the pivot keeps being the largest or smallest value of the range, because then each round drops only that one value.
A sorted array with k = nk = nk = n / 2
A random pivot does not help when all values are equal: with k = 1
Another way: a heap of size k
A min-heap is a structure that always hands out its smallest value first. In Java, PriorityQueue
This takes O(n log k) time, more than Quickselect's average, but it never changes nums
Java Solution
The method findKthLargest
- First, work out
, the index n - k where the answer would sit in the sorted array.target andleft mark the range still searched, at first the whole array.right - In a loop, partition the range with the helper method
. It takes the last value of the range as the pivot, moves every smaller value to its left using the indexpartition , puts the pivot right after them, and returns the indexstore where the pivot landed. A small helper,p , exchanges two values.swap - If
is the target, return the value there. If it is left of the target, keep searching right of it, sop becomesleft . If it is right of the target,p + 1 becomesright .p - 1
For comparison, the class also has the heap version, findKthLargestHeapPriorityQueuerun
The maink = 1k = n
import java.util.Arrays;
import java.util.PriorityQueue;
public class FindKthLargest {
// Quickselect: the k-th largest sits at index n - k once the array is sorted
public static int findKthLargest(int[] nums, int k) {
int target = nums.length - k;
int left = 0;
int right = nums.length - 1;
while (true) {
int p = partition(nums, left, right);
if (p == target) {
return nums[p];
} else if (p < target) {
left = p + 1; // the answer is right of the pivot
} else {
right = p - 1; // the answer is left of the pivot
}
}
}
// Smaller values go left of the pivot; returns the index where the pivot lands
private static int partition(int[] a, int left, int right) {
int pivot = a[right];
int store = left;
for (int i = left; i < right; i++) {
if (a[i] < pivot) {
swap(a, i, store++);
}
}
swap(a, store, right);
return store;
}
private static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
// Min-heap of the k largest values seen so far: its top is the k-th largest
public static int findKthLargestHeap(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) {
heap.poll(); // drop the smallest of the k + 1
}
}
return heap.peek();
}
static void run(int[] nums, int k) {
String input = Arrays.toString(nums);
int byHeap = findKthLargestHeap(nums, k);
int byQuickselect = findKthLargest(nums, k);
System.out.println(input + ", k = " + k + " -> quickselect " + byQuickselect
+ ", heap " + byHeap);
}
public static void main(String[] args) {
run(new int[] {3, 2, 1, 5, 6, 4}, 2);
run(new int[] {3, 2, 3, 1, 2, 4, 5, 5, 6}, 4);
run(new int[] {3, 2, 1, 5, 6, 4}, 1); // the largest
run(new int[] {3, 2, 1, 5, 6, 4}, 6); // the smallest
run(new int[] {5, 5, 5, 5}, 3); // all values the same
run(new int[] {-1, -7, 0, -3}, 2); // negative numbers
run(new int[] {42}, 1); // a single value
int[] nums = {3, 2, 1, 5, 6, 4};
findKthLargest(nums, 2);
System.out.println("after quickselect: " + Arrays.toString(nums));
}
}
Running it prints:
[3, 2, 1, 5, 6, 4], k = 2 -> quickselect 5, heap 5
[3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 -> quickselect 4, heap 4
[3, 2, 1, 5, 6, 4], k = 1 -> quickselect 6, heap 6
[3, 2, 1, 5, 6, 4], k = 6 -> quickselect 1, heap 1
[5, 5, 5, 5], k = 3 -> quickselect 5, heap 5
[-1, -7, 0, -3], k = 2 -> quickselect -1, heap -1
[42], k = 1 -> quickselect 42, heap 42
after quickselect: [3, 2, 1, 4, 5, 6]
The first two lines are the examples, and both methods agree: 5 and 4. The next two lines ask Example 1 for its largest and its smallest value, 6 and 1, so the target works at both ends of the array. In [5, 5, 5, 5]
Look at the last line. After Quickselect, the array reads [3, 2, 1, 4, 5, 6]. That is the result of the first partition from the picture, plus the second partition, which swapped 6 and 5. So findKthLargestnums.clone()run
The original implementation and its tests are on GitHub:
Complexity
Quickselect spends its time in partitions, and each partition costs one comparison per value in the current range.
- Time: O(n) on average, O(n²) in the worst case. A good pivot roughly halves the range, so the work is about n + n/2 + n/4 + ..., which stays under 2n. A pivot that is always the largest or smallest of the range drops one value per round, which gives about n²/2 comparisons.
- Space: O(1) extra. The array is rearranged in place, and the loop only moves
andleft . The heap version needs O(k) space for the heap and O(n log k) time, since each value costs at most one add and one remove on a heap of at most k + 1 values.right
The partition step is also the heart of