Kth Largest Element in Java: Explanation & Practice

Find the kth largest element in array

Problem summary

Given an unsorted array, find the kth largest element. Use min-heap of size k for O(n log k) solution.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {3, 2, 1, 5, 6, 4};
        int k = 2;
        
        // Min-heap of size k
        // After processing all, top is kth largest
        // Print: Kth largest: 5
    }
}

Expected output and test cases

  • [3,2,1,5,6,4], k=2 → 5
    Kth largest: 5
  • [3,2,3,1,2,4,5,5,6], k=4
    Kth largest: 4
  • [1], k=1 → 1
    Kth largest: 1

Hints

  1. Use min-heap (PriorityQueue in Java)
  2. Keep heap size at most k
  3. If heap size > k, remove smallest (poll)
  4. After all elements, heap top is kth largest

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler