Introduction
Kth Largest Element means:
- finding the kth largest value
from an unsorted array
efficiently
Goal:
- avoid full sorting
- use heap optimization
Example:
Array:[3,2,1,5,6,4]k = 2
Output:
5
Explanation:
Sorted Order:[1,2,3,4,5,6]
2nd largest element: 5
This problem is one of the most important applications of:
Min Heap Constraints
1 <= Array Size <= 10^5 Approach : Min Heap
Explanations:
Explanation:
The idea is:
- maintain only k elements
inside heap - smallest heap element
becomes kth largest answer
Steps:
- Create Min Heap.
- Insert current element.
- Keep heap size as k.
- Remove smallest element.
- Continue traversal.
- Heap top becomes answer.
Condition:
Heap Size > k Remove top element Observation:
Heap always stores k largest elements. This approach:
- avoids sorting
- efficiently finds kth largest value
Dry Run
Array:[3,2,1,5,6,4]
k = 2
Heap:
[3]
[2,3]
Add 1
Heap size > 2
Remove 1
Heap:
[2,3]
Add 5
Remove 2
Heap:
[3,5]
Add 6 Remove 3
Heap:
[5,6]
Add 4 Remove 4
Heap:
[5,6]
Answer:
5
Practice :