Skip to content

Kth Largest Element

Topic: 10. Heaps

Link: LeetCode 215 - Kth Largest Element in an Array

1. Logical Breakdown

  • [x] Core Logic: Min-Heap of size K.
  • [x] Result: The root of the heap is the Kth largest.

2. Visualization

graph TD Add["Add to Min-Heap"] --> Check["Size > K?"] Check -- Yes --> Pop["Pop Smallest"] Check -- No --> Continue

3. Complexity

  • Time: O(N log K)
  • Space: O(K)

4. Code

package com.dsa.heaps;
import java.util.PriorityQueue;

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