# Kth Largest Element In A Stream Problem

## Description

LeetCode Problem 703.

Design a class to find the k^th largest element in a stream. Note that it is the k^th largest element in the sorted order, not the k^th distinct element.

Implement KthLargest class:

• KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
• int add(int val) Appends the integer val to the stream and returns the element representing the k^th largest element in the stream.

Example 1:

``````1
2
3
4
5
6
7
8
9
10
11
12
Input
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]
Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
``````

Constraints:

• 1 <= k <= 10^4
• 0 <= nums.length <= 10^4
• -10^4 <= nums[i] <= 10^4
• -10^4 <= val <= 10^4
• It is guaranteed that there will be at least k elements in the array when you search for the k^th element.

## Sample C++ Code

``````1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class KthLargest {
public:
priority_queue<int,vector<int>,greater<int>> pq;
int K;

KthLargest(int k, vector<int>& nums) {
K = k;
for (int i = 0; i < nums.size(); i ++)
}

pq.push(val);
if (pq.size() > K)
pq.pop();
return pq.top();
}
};

/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest* obj = new KthLargest(k, nums);
*/
``````