Heap / Priority Queue
Medium
Kth Largest Element in an Array
Find the kth largest element in an unsorted array.
10 min read
Solve on LeetCodeProblem Understanding
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
Example 2:
- Input:
nums = [3,2,3,1,2,4,5,5,6],k = 4 - Output:
4
Algorithm Strategy
We can use a Min-Heap to efficiently find the Kth largest element.
- Initialize a Min-Heap: We will maintain a heap of size
k. - Iterate through the array: For each number:
- Push it onto the heap.
- If the heap size exceeds
k, pop the smallest element (root).
- Result: After processing all numbers, the heap contains the
klargest elements. The smallest of these (the root) is exactly thekth largest element.
Why Min-Heap?
We want to keep the "largest" elements. By popping the smallest element whenever we exceed size K, we discard the "small" numbers and keep the "large" ones.
Interactive Visualization
Step 1 / 1
Empty Heap
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
