Kth Largest Element in an Array

Pattern: Top K

medium

Push values into a min heap and pop whenever it holds more than k. After the pass, the heap holds the k largest and its top is the kth largest. O(n log k).

The problem

Return the kth largest value in the array, counting duplicates (so in [3, 3, 2] the 2nd largest is 3). [3, 2, 1, 5, 6, 4] with k = 2 gives 5.

Think first

  • What does sorting give, and at what cost?
  • Do you need all values in order?
  • Which values must you keep while scanning?

Hints

    Brute force, and why it fails

    Sort and index: O(n log n). Quickselect is O(n) on average but O(n²) in the worst case.

    The key insight

    A size-k min heap throws out anything that cannot be in the top k, so each value costs O(log k).

    Dry run

    heap2 3

    nums = [3, 2, 1, 5, 6, 4], k = 2. Push 3, 2: heap 2, 3. Push 1: pop 1.

    Step 1 of 3

    The plan

    heap = empty min heap
    for x in nums: push x; if size > k: pop
    return top
    

    Complexity

    Time
    O(n log k)
    Space
    O(k)

    n pushes and pops on a heap of at most k + 1.

    Edge cases

    • k = 1: the maximum.
    • k = n: the minimum.
    • Duplicates count separately.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int findKthLargest(int[] nums, int k) {
            PriorityQueue<Integer> heap = new PriorityQueue<>();   // min heap of the k largest seen
            for (int x : nums) {
                heap.add(x);
                if (heap.size() > k) heap.poll();
            }
            return heap.peek();
        }
    }

    C++

    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            priority_queue<int, vector<int>, greater<int>> heap;   // min heap of the k largest seen
            for (int x : nums) {
                heap.push(x);
                if (static_cast<int>(heap.size()) > k) heap.pop();
            }
            return heap.top();
        }
    };

    Python

    import heapq
    
    class Solution:
        def findKthLargest(self, nums: list[int], k: int) -> int:
            heap = []                               # min heap of the k largest seen
            for x in nums:
                heapq.heappush(heap, x)
                if len(heap) > k:
                    heapq.heappop(heap)
            return heap[0]

    Common mistakes

    • Removing duplicates first.
    • Returning the kth smallest by keeping a max heap.

    Similar problems