Kth Largest Element

Given an unsorted array, find the kth largest element.

Example

([3,2,1,5,6,4], 2) => 5

Brute Force

Sort the input array. Then return the n-k smallest element.

Arrays.sort(nums);
return nums[nums.length - k];

Priority Queue

We need to somehow structure this unstructured data. Maintain a min heap of size k. Poll as we go.

public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
    for (int num : nums) {
        minHeap.offer(num);
        if (minHeap.size() > k) {
            minHeap.poll();
        }
    }
    return minHeap.peek();
}

Time O(nlogk) Space O(k)

Quick Select

A true linear time algorithm doesn't exist for an unsorted array. But we can randomly pick a pivot and hope that it will structure some parts of the data. We can use the partition step from quick sort to help us to do that.

Be mindful on the post condition after partition. j becomes the end the smaller section and i becomes the start of the larger section.

Time O(n) on average because the geometric sum proves T(n) = O(n) + T(n/2) = O(n).

Median Variant (LI.80arrow-up-right)

k=length/2 if even k=length/2 + 1 if odd

Mailbox Variant (EPIarrow-up-right)

Given an unordered list of building objects, find the best place a mailbox to minimize the total distance.

Last updated