Problem
Design a class that finds the kth largest value in a stream of numbers. A stream is a sequence of numbers that arrive one at a time.
The kth largest value is the value at position k when you sort all the numbers from the largest to the smallest. Equal numbers count as separate items.
Write the class KthLargest with these operations:
KthLargest(k, nums) creates the object with the integer k and the first numbers nums. add(val) adds the integer val to the stream. Then it returns the kth largest value of all the numbers so far.
Example 1
- Input:
- ["KthLargest","add","add","add","add"] [[2,[5,1,8]],[3],[10],[9],[2]]
- Output:
- [null,5,8,9,9]
- Explanation:
- After
add(3), the numbers are[5, 1, 8, 3], and the 2nd largest value is 5. Afteradd(10), the 2nd largest value is 8.
Example 2
- Input:
- ["KthLargest","add","add","add"] [[1,[]],[-4],[-7],[0]]
- Output:
- [null,-4,-4,0]
- Explanation:
- With
k = 1, each call toaddreturns the largest value so far.
Constraints
- 1 <= k <= 10^4
- 0 <= nums.length <= 10^4
- -10^4 <= nums[i] <= 10^4
- -10^4 <= val <= 10^4
- At most 10^4 calls to add
- The stream has at least k numbers after each call to add.
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
- Find the kth largest element in an unsorted array
Coding
- Kth Largest Element in an Array
Coding · Array · Divide and Conquer · Heap (Priority Queue)
- Find Kth Largest XOR Coordinate Value
Coding
- Find Second Largest Element in an Array
Coding
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 2 records
Cloudkitchens
Leetcode 703. Kth Largest Element in a Stream
Reported Jun 2, 2025 · 1 source report
SENIOR
Source snapshot: Nov 12, 2026
View sourceMicrosoft
Leetcode 703. Kth Largest Element in a Stream
Reported Feb 4, 2026 · 1 source report
SENIOR
Source snapshot: Nov 12, 2026
View source