Java Heap Program · OT45
Find the Kth Largest Element in Java
Keep only the k largest values seen so far in a min-heap. The smallest of them, at the top of the heap, is the k-th largest overall.
Problem Statement
Given an array and an integer k, return the k-th largest element, counting duplicates as separate elements.
Assume 1 ≤ k ≤ n. The array should not need to be fully sorted.
Input/Output Examples
[7, 10, 4, 3, 20, 15], k = 3Output10Explanation: the largest three are 20, 15 and 10.[7, 10, 4, 3, 20, 15], k = 1Output20Explanation: the maximum.[5, 5, 5], k = 2Output5Explanation: duplicates count separately.Visual Explanation
- 7, 10, 4heap4710size 3
- 3heap47103 enters, 3 is polled
- 20heap710204 is polled
- 15heap1015207 is polled
- Donepeek() = 10
[7, 10, 4, 3, 20, 15]: whenever it grows to 4, the smallest value leaves. The top (purple) is the 3rd largest.The heap never holds more than k + 1 values, so each insertion costs O(log k) instead of O(log n).
Approaches
The heap is simple and works on streams. Quickselect is faster on average for a single array.
Approach 1: Min-Heap of Size k (Recommended)
Idea: offer every value to a PriorityQueue; when it holds more than k values, poll the smallest.
- Create a
PriorityQueue<Integer>, which is a min-heap by default. - Add each value; if the size exceeds
k, callpoll(). - Return
peek().
Time: O(n log k) · Space: O(k).
Approach 2: Quickselect
Idea: partition around a pivot like quicksort, then continue only in the side that contains index n - k.
- Copy the array and set the target index to
n - kin ascending order. - Partition the current range around the middle element.
- If the pivot lands on the target, return it; otherwise narrow to one side.
Time: O(n) average · Space: O(1). Excluding the copy; the worst case is O(n²).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Min-Heap of Size k (Recommended)
Also works when the numbers arrive one at a time and the array is never fully available.
import java.util.Arrays;
import java.util.PriorityQueue;
public class KthLargestHeap {
// A min-heap of the k largest values seen so far; its top is the k-th largest
static int kthLargest(int[] arr, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int v : arr) {
heap.offer(v);
if (heap.size() > k) {
heap.poll(); // drop the smallest of the k + 1
}
}
return heap.peek();
}
public static void main(String[] args) {
int[] arr = {7, 10, 4, 3, 20, 15};
System.out.println(Arrays.toString(arr) + ", k=3 -> " + kthLargest(arr, 3));
System.out.println(Arrays.toString(arr) + ", k=1 -> " + kthLargest(arr, 1));
System.out.println("[5, 5, 5], k=2 -> " + kthLargest(new int[] {5, 5, 5}, 2));
}
}
[7, 10, 4, 3, 20, 15], k=3 -> 10 [7, 10, 4, 3, 20, 15], k=1 -> 20 [5, 5, 5], k=2 -> 5
Time complexity: O(n log k) · Space complexity: O(k).
Approach 2: Quickselect
Only one side is processed after each partition, so the expected work is linear.
import java.util.Arrays;
public class KthLargestQuickselect {
// Partition like quicksort, but recurse only into the side that holds the answer
static int kthLargest(int[] arr, int k) {
int[] a = arr.clone();
int target = a.length - k; // index in ascending order
int lo = 0;
int hi = a.length - 1;
while (true) {
int p = partition(a, lo, hi);
if (p == target) {
return a[p];
} else if (p < target) {
lo = p + 1;
} else {
hi = p - 1;
}
}
}
// Lomuto partition with the middle element as pivot
private static int partition(int[] a, int lo, int hi) {
int mid = lo + (hi - lo) / 2;
swap(a, mid, hi);
int pivot = a[hi];
int store = lo;
for (int i = lo; i < hi; i++) {
if (a[i] < pivot) {
swap(a, i, store++);
}
}
swap(a, store, hi);
return store;
}
private static void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static void main(String[] args) {
int[] arr = {7, 10, 4, 3, 20, 15};
System.out.println(Arrays.toString(arr) + ", k=3 -> " + kthLargest(arr, 3));
System.out.println(Arrays.toString(arr) + ", k=1 -> " + kthLargest(arr, 1));
System.out.println("[5, 5, 5], k=2 -> " + kthLargest(new int[] {5, 5, 5}, 2));
}
}
[7, 10, 4, 3, 20, 15], k=3 -> 10 [7, 10, 4, 3, 20, 15], k=1 -> 20 [5, 5, 5], k=2 -> 5
Time complexity: O(n) average · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Min-Heap of Size k | O(n log k) | O(k) |
| Quickselect | O(n) average | O(1) |
Here n is the array length. The heap processes every value with O(log k) work; quickselect averages O(n) but can degrade with unlucky pivots.
Interview Tips and Recommended Approach
- Use a min-heap for the k largest. A max-heap of all values works too but uses
O(n)memory. - Count duplicates unless the question asks for distinct values.
- Explain quickselect's worst case and how random pivots avoid it in practice.
- Mention sorting as the
O(n log n)baseline.
Recommended Approach: Min-Heap of Size k
Why: it is short, hard to get wrong, uses little memory and also works on data streams.