← Back to DSA Animator
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.