Kth Largest Element in a Stream - Problem

You are part of a university admissions office and need to keep track of the kth highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores.

You are tasked to implement a class which, for a given integer k, maintains a stream of test scores and continuously returns the kth highest score after a new score has been submitted.

More specifically, we are looking for the kth highest score in the sorted list of all scores.

Implement the KthLargest class:

  • KthLargest(int k, int[] nums) - Initializes the object with the integer k and the stream of test scores nums
  • int add(int val) - Adds a new test score val to the stream and returns the element representing the kth largest element in the pool of test scores so far

Input & Output

Example 1 — Basic Operations
$ Input: k = 3, nums = [4,5,8,2], operations = [["add",3],["add",5],["add",10],["add",9],["add",4]]
Output: [4,5,5,8,8]
💡 Note: Initial: [8,5,4] are 3 largest. Add 3→4th largest is 4. Add 5→still 4. Add 10→now 5. Add 9→now 8. Add 4→still 8.
Example 2 — Minimum Size
$ Input: k = 1, nums = [1], operations = [["add",2],["add",0]]
Output: [2,2]
💡 Note: k=1 means always return the maximum. After adding 2, max is 2. After adding 0, max is still 2.
Example 3 — Empty Initial Array
$ Input: k = 2, nums = [], operations = [["add",5],["add",3],["add",7]]
Output: [5,3,5]
💡 Note: Add 5: only element so 2nd largest is 5. Add 3: 2nd largest is 3. Add 7: 2nd largest becomes 5.

Constraints

  • 1 ≤ k ≤ 104
  • 0 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • -104 ≤ val ≤ 104
  • At most 104 calls will be made to add

Visualization

Tap to expand
Kth Largest in Stream: k=3, track 3rd largest scoreInitial:4582Add 3:854323rd→ 4Add 5:855433rd→ 5Add 10:1085543rd→ 5Results:45588Stream of 3rd largest scores: [4, 5, 5, 8, 8]
Understanding the Visualization
1
Initialize
Start with k=3 and initial scores [4,5,8,2]
2
Stream Processing
Add new scores one by one: 3, 5, 10, 9, 4
3
Track Results
Return 3rd largest after each addition: [4,5,5,8,8]
Key Takeaway
🎯 Key Insight: Use a min-heap of size k to efficiently track the k largest elements
Asked in
Amazon 15 Google 12 Facebook 8 Apple 6
125.0K Views
High Frequency
~25 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen