1 min read
https://practice.geeksforgeeks.org/problems/kth-smallest-element/0
- Make priority queue of size
k
, insert firstk
elements from the array - For the remaining elements, pop and insert into pq if element is smaller than top
class Solution {
public:
int kthSmallest(int arr[], int l, int r, int k) {
priority_queue<int, vector<int>> pq(arr, arr + k);
int n = r - l + 1;
for (int i = k; i < n; i++) {
if (arr[i] < pq.top()) {
pq.pop();
pq.push(arr[i]);
}
}
return pq.top();
}
};