DSA AnimatorDSA animations
Kth Largest Element in an Array LC #215 Medium Heap · Top-K Filter
Problem

Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Explanation: Sorted descending: [6,5,4,3,2,1] → 2nd largest = 5.
Example 2
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Explanation: Sorted descending: [6,5,5,4,...] → 4th largest = 4.
Constraints: 1 ≤ k ≤ nums.length ≤ 10⁵  |  -10⁴ ≤ nums[i] ≤ 10⁴
Try Examples
Custom:
Approach
Min Heap of Size K — Window of the K Largest Seen
The heap root = smallest of the k largest = kth largest. When full, evict the min to keep only the top-k.
Input Array
Min-Heap (size K)
Top-K Candidates
Size: 0 / —
root = Kth Largest
Select an example above and press Play.
Variables
Current num
—
Heap Size
0
Heap Root (Kth so far)
—
k
—
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Create a min-heap (PriorityQueue) of size k
2
For each element: add it to the heap
3
If heap size > k: evict the root (smallest element)
4
Return heap root = min of k largest = kth largest
Time
O(n log k)
Space
O(k)
Why Min-Heap of Size K?

A min-heap of size k always holds the k largest elements seen so far. Its root is the smallest of those k — which is exactly the kth largest. When a new element comes in and pushes the heap to size k+1, we evict the minimum (root). This ensures we always keep the top-k candidates. At the end, the root is the answer.

How to solve Kth Largest Element in an Array

LeetCode 215 · Medium · Heap / Priority Queue · Pattern: Min Heap of Size K

Why the obvious approach is slow

Sorting the whole array and picking index n minus k works in O(n log n). But we only care about the top k values, not the full order.

The key idea

Keep a min heap that holds at most k numbers. It always stores the k largest numbers seen so far. The smallest of those k sits at the root, so the root is the k-th largest so far. For every new number, push it, and if the heap grows beyond k, poll the root. At the end, the root is the answer.

Remember

For the k largest, use a min heap of size k. The root of that heap is the k-th largest.

Run the animation above on your own input, or watch the 1:51 video explanation of Kth Largest Element in an Array with a dry run and Java code.

More Heap / Priority Queue problems