Skip to main content
LeetCode 703, Easy. Topics: Tree, Design, Binary Search Tree, Heap (Priority Queue), Binary Tree, Data Stream. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 13 parametrized pytest cases, and a playground notebook:

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 test 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 k<sup>th</sup> largest element in the pool of test scores so far.

Examples

Constraints

  • 0 <= nums.length <= 10<sup>4</sup>
  • 1 <= k <= nums.length + 1
  • -10<sup>4</sup> <= nums[i] <= 10<sup>4</sup>
  • -10<sup>4</sup> <= val <= 10<sup>4</sup>
  • At most 10<sup>4</sup> calls will be made to add.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode 150, NeetCode 250, NeetCode All.
Last modified on August 25, 2026