Kth Largest Element in an Array - Top K Elements Pattern

Kth Largest Element in an Array in Java using the Top K Elements pattern: problem statement, approach, template, complexity, and interview tips.

Kth Largest Element in an Array

Problem Statement

Return the kth largest element in an unsorted array.

Pattern: Top K Elements

Use a heap of size k (or a selection algorithm) to keep only the best k items while scanning the input.

Use this pattern when the question asks for the k largest, smallest, most frequent or closest items, or merges several sorted sources.

Approach

  1. Pick a min-heap for the k largest or a max-heap for the k smallest.
  2. Offer each item and drop the worst one when the heap exceeds k.
  3. Read the answer from the heap at the end.

Pattern Template (Java)

PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
for (int x : nums) {
    heap.offer(x);
    if (heap.size() > k) {
        heap.poll();
    }
}
// heap.peek() is the kth largest

Adapt this template to the exact rules of Kth Largest Element in an Array: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(n log k) time and O(k) space.

Interview Tips

  • Mention quickselect as an O(n) average alternative.
  • Use a comparator for custom ordering such as distance or frequency.
  • Start with a brute-force idea, state its complexity, then explain how the Top K Elements pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Next: Top K Frequent Elements

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.