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 nums, in no particular order, and a number k between 1 and the length of the array. Return the k-th largest value: the value that would be k-th from the end if the array were sorted from smallest to largest. Repeated values count separately, so this is not the k-th largest distinct value.

Example 1
Input: nums = [3, 2, 1, 5, 6, 4], k = 2
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
Input: nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
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.
Solution

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 = 1 is the top score, k = 2 the runner-up. Here the scores are the values in nums.

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 is 5. In terms of positions, the six values sit at indexes 0 to 5, and 5 sits at index 4. In general the k-th largest value sits at index n - k of the sorted array, where n is the length. We will call that index the target.

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.

Partitioning 3, 2, 1, 5, 6, 4 around the pivot 4 gives 3, 2, 1, 4, 6, 5. The values smaller than 4 are on its left, the larger ones on its right, and 4 lands at index 3. The target index 4 is in the right part.

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) followed by nums[n - k] is correct and short. It costs O(n log n) time, though, because it orders every value, and the order of all the others is never used.

Quickselect looks for the same index, target = n - k. The largest value belongs at the last index, n - 1, and the smallest at index 0. Aiming at index k - 1 instead would find the k-th smallest value: 2, not 5, for Example 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, store, starts at the left end and marks where the next smaller value goes. One pass compares every other value with the pivot. A smaller value is swapped into position store, and store moves one step right.

In Example 1, 3, 2 and 1 are each smaller than 4. Each swaps with itself, since it is already at store, and store moves to 3. 5 and 6 are not smaller, so nothing moves. Finally the pivot swaps with the value at store, the 5 at index 3, which gives [3, 2, 1, 4, 6, 5] from the picture.

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, left and right, mark the range that can still hold the answer, at first the whole array. If the pivot lands on the target, the search is over. If it lands left of the target, the range becomes everything right of the pivot. If it lands right of the target, the range becomes everything left of it.

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 = n does exactly that. Counting the comparisons of the partition used below, 10,000 sorted values with k = n took 49,995,000. The same values shuffled, with k = n / 2, took 46,078. An optional improvement is to swap a randomly chosen value to the end before each partition. With that change, the sorted case took 34,094 comparisons.

A random pivot does not help when all values are equal: with k = 1 it still took 49,995,000 comparisons. Handling that case needs a partition that keeps the values equal to the pivot in a middle group of their own.

Another way: a heap of size k

A min-heap is a structure that always hands out its smallest value first. In Java, PriorityQueue is one. Add the values one by one, and whenever the heap holds k + 1 values, remove its smallest. What stays is the k largest values seen so far, and the smallest of them, at the top, is the k-th largest.

This takes O(n log k) time, more than Quickselect's average, but it never changes nums and has no bad cases. It also suits values that arrive one at a time.

Java Solution

The method findKthLargest runs Quickselect in these steps:

  1. First, work out target, the index n - k where the answer would sit in the sorted array. left and right mark the range still searched, at first the whole array.
  2. In a loop, partition the range with the helper method partition. It takes the last value of the range as the pivot, moves every smaller value to its left using the index store, puts the pivot right after them, and returns the index p where the pivot landed. A small helper, swap, exchanges two values.
  3. If p is the target, return the value there. If it is left of the target, keep searching right of it, so left becomes p + 1. If it is right of the target, right becomes p - 1.

For comparison, the class also has the heap version, findKthLargestHeap, which keeps a PriorityQueue of at most k + 1 values, and a method run that prints one input with the answers of both.

The main method runs both examples, then k = 1 and k = n, equal values, negative numbers and a single value, and finally prints an array after Quickselect has run on it.

Java
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:

Output
[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] every place holds 5. With negative numbers the second largest is -1, just below 0, and a single value is its own answer.

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 findKthLargest reorders the caller's array. Pass nums.clone() when the original order matters. This is also why run calls the heap version first, before Quickselect moves the values around.

The original implementation and its tests are on GitHub: KthLargestElement.java and TestKthLargestElement.java.

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 left and right. 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.

The partition step is also the heart of Quick Sort, which partitions both sides instead of one.